You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Prisma Comment模型如何设置自关联实现评论多回复并解决歧义报错

错误原因

自关联的两个反向字段未指定相同的关联名称,导致Prisma无法识别二者的关联配对关系。

解决方案

给两个自关联字段配置相同的@relation名称即可,同时建议调整字段名提高语义可读性,修改后的模型如下:

model Comment {
 id            Int             @id @default(autoincrement())
 text          String          @db.VarChar
 rating        Int             @default(0)
 createdAt     DateTime        @default(now()) @db.Timestamp(6)
 creatorId     Int
 postId        Int?
 repliedToId   Int?
 user          User            @relation(fields: [creatorId], references: [id])
 post          Post?           @relation(fields: [postId], references: [id])
 // 指向当前评论回复的父评论
 repliedTo     Comment?        @relation("CommentReplyRelation", fields: [repliedToId], references: [id])
 // 指向当前评论收到的所有子回复
 replies       Comment[]       @relation("CommentReplyRelation")
 CommentRating CommentRating[]
}

验证效果

配置后可直接满足单条评论多条回复的需求,查询关联数据的方式如下:

  • 查询某条评论的所有回复:查询时添加include: { replies: true }参数
  • 查询某条回复对应的父评论:查询时添加include: { repliedTo: true }参数

内容的提问来源于stack exchange,提问作者yasermoamd

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.25 13:54:06