如何在Prisma中正确设计关联Post和Comment的Like模型?
问题分析
你的Like模型存在两个核心问题:
postId和commentId被定义为必填Int,但业务逻辑中一个点赞只能关联帖子或评论其中之一,无法同时关联两者- 复合主键
@@id([userId, postId, commentId])要求三个字段必须同时有值,导致无法创建仅关联帖子/评论的合法点赞记录
正确的Like模型设计
推荐使用自增主键+可选外键+唯一约束的方案,既符合业务逻辑,又保证数据完整性:
model User { id Int @id @default(autoincrement()) email String @unique username String password String refreshToken String? createdAt DateTime @default(now()) avatar String? cover String? bio String? comments Comment[] likes Like[] posts Post[] } model Post { id Int @id @default(autoincrement()) content String authorId Int images String[] createdAt DateTime @default(now()) comments Comment[] likes Like[] author User @relation(fields: [authorId], references: [id]) } model Comment { id Int @id @default(autoincrement()) content String authorId Int postId Int author User @relation(fields: [authorId], references: [id]) post Post @relation(fields: [postId], references: [id]) likes Like[] } model Like { id Int @id @default(autoincrement()) userId Int postId Int? // 可选:仅点赞帖子时填写 commentId Int? // 可选:仅点赞评论时填写 createdAt DateTime @default(now()) user User @relation(fields: [userId], references: [id]) post Post? @relation(fields: [postId], references: [id], onDelete: Cascade) comment Comment? @relation(fields: [commentId], references: [id], onDelete: Cascade) // 约束:用户不能重复点赞同一个帖子 @@unique([userId, postId], name: "unique_like_post") // 约束:用户不能重复点赞同一个评论 @@unique([userId, commentId], name: "unique_like_comment") // 约束:每个点赞必须关联帖子或评论中的一个 @@check(postId != null || commentId != null) }
设计说明
- 用自增
id作为主键,避免复合主键的限制,后续扩展字段更灵活 postId和commentId设为可选类型Int?,允许仅填写其中一个,符合“点赞要么属于帖子要么属于评论”的逻辑- 两个
@@unique约束确保用户对同一帖子/评论只能点赞一次,防止重复数据 @@check约束强制每个点赞必须关联帖子或评论,避免空关联的无效数据onDelete: Cascade配置保证帖子/评论被删除时,对应的点赞会自动清理,避免脏数据
内容的提问来源于stack exchange,提问作者iufb
相关产品推荐
相关产品推荐

