如何通过Prisma的Cascade实现评论及回复的一键级联删除?
解决评论父级删除时自动级联删除子回复的问题
你的问题出在自关联的删除策略设置上——当前子评论关联父评论的onDelete属性是NoAction,这导致父评论被删除时,数据库会因为存在关联的子评论而阻止操作。只需要修改这个属性为Cascade,就能实现删除父评论时自动删除所有关联的子回复。
修改后的Comment模型代码如下:
model Comment { id Int @id @default(autoincrement()) content String @db.MediumText replyId Int? reply Comment? @relation(name: "ReplyComments", fields: [replyId], references: [id], onDelete: Cascade, onUpdate: NoAction) comments Comment[] @relation(name: "ReplyComments") user User @relation(fields: [userId], references: [id], onDelete: Cascade) userId String post Post @relation(fields: [postId], references: [id], onDelete: Cascade) postId Int hearts CommentHeart[] createdAt DateTime @default(now()) updatedAt DateTime @updatedAt @@index([userId]) @@index([postId]) @@index([replyId]) }
关键修改说明
- 将
reply字段的onDelete: NoAction改为onDelete: Cascade,这意味着当父评论(即当前子评论关联的reply对象)被删除时,所有关联它的子评论会被数据库自动级联删除。 - 修改后,你只需要发送一次删除父评论的查询,数据库会自动处理所有子回复的删除操作,无需提前手动删除子评论。
内容的提问来源于stack exchange,提问作者SeongBaek CHO
相关产品推荐
相关产品推荐

