如何解决Prisma 约束以确保数据库中的单个项目
我的 Prisma 架构中有一个 Category
模型,它有一个名为 parent
的字段:
model Category {
id Int @default(autoincrement()) @id
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
title String @unique
parent Boolean
parentId Int?
stores Storefront[]
products Product[]
}
如何确保始终至少有 1 个 Category
的 parent
为真?如果没有,则发回错误。我是否必须在突变中手动执行此操作?
例如,updateCategory 突变:
export default async function updateCategory({ where,data }: UpdateCategoryInput,ctx: Ctx) {
const { title,parent,parentId } = CategoryInput.parse(data)
const category = await db.category.update({
where,data: {
title,parentId: parent ? null : parentId,},})
return category
}
解决方法
这似乎是您必须在更新前在解析器中实现的业务逻辑,我不认为这可以通过在数据库或 Prisma 级别设置约束来实现。
以下是我建议在您的应用程序中强制执行此约束的建议:
export default async function updateCategory({ where,data }: UpdateCategoryInput,ctx: Ctx) {
const { id,title,parent,parentId } = CategoryInput.parse(data)
// Check how many categories there are with `parent` set to `true`
const categories = await db.category.findMany({
where: { parent: true }
})
if (categories.length === 1 && categories[0].id === id && !parent) {
// if all these conditions are true,you are about to set the last
// category with `parent` equals `true` to `false` which must not happen
throw new Error(`This mutation would set the last parent to false`)
}
const category = await db.category.update({
where: {
id: id
},data: {
title,parentId: parent ? null : parentId,},})
return category
}
请注意,您必须将此检查添加到应用程序中 parent
可能设置为 false
的每个部分。
让我知道这是否有帮助或您有任何其他问题:)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。