我正在尝试在数据库中插入一行,前提是 - 表中已经满足某些条件的行数小于某个阈值,例如 10。例如,在下面的模型中,我不想让一个项目拥有更多超过 10 个用户;所以count(projectId)
应该小于 10:
model User {
id BigInt @id @default(autoincrement())
firstName String @map("first_name")
lastName String @map("last_name")
email String @unique
password String
passwordHash String @map("password_hash")
createdAt DateTime @db.Timestamptz() @default(now()) @map("created_at")
updatedAt DateTime @db.Timestamptz() @updatedAt @map("updated_at")
project Project @relation(fields: [projectId], references: [id])
projectId BigInt? @map("project_id")
@@map("app_user")
}
model Project {
id BigInt @id @default(autoincrement())
name String
users User[]
@@map("project")
}
在一般的 SQL 世界中,我会依赖事务与乐观并发控制,然后仅在读取匹配的行数后尝试插入project_id
。由于 Prisma 不提供传统的长时间运行的事务,我被卡住了。我不能只是简单地先运行计数查询然后再进行插入,因为它本质上不是原子的。
如何使用 Prisma 处理这种情况?