如何在Prisma中创建Friendship模型?关联名称重复报错求助
解决Prisma中Friendship模型的关系命名冲突问题
在开发类Facebook应用时,构建Friendship模型遇到Prisma验证错误:
Error validating model "Friendship": Wrongly named relation detected. The fields
userandfriendin modelFriendshipboth use the same relation name. Please provide different relation names for them through@relation().
原User模型代码:
model User { id String @id handle String @unique created_at DateTime @default(now()) updated_at DateTime @updatedAt account Account @relation(fields: [id], references: [id]) }
原Friendship模型代码:
model Friendship { id String @id @default(cuid()) user_id String user User @relation(name: "friendships", fields: [user_id], references: [id]) friend_id String friend User @relation(name: "friendships", fields: [friend_id], references: [id]) created_at DateTime @default(now()) updated_at DateTime @updatedAt @@unique([user_id, friend_id]) @@unique([friend_id, user_id]) }
解决方案
问题核心是两个@relation使用了相同的name参数,Prisma要求同一模型内的不同关系必须有唯一名称。同时需要在User模型中添加对应的反向关系,让Prisma正确识别双向关联。
修改后的User模型
model User { id String @id handle String @unique created_at DateTime @default(now()) updated_at DateTime @updatedAt account Account @relation(fields: [id], references: [id]) // 当前用户发起的好友关系 friendshipsAsUser Friendship[] @relation(name: "UserFriendships") // 当前用户收到的好友关系 friendshipsAsFriend Friendship[] @relation(name: "FriendUserFriendships") }
修改后的Friendship模型
model Friendship { id String @id @default(cuid()) user_id String user User @relation(name: "UserFriendships", fields: [user_id], references: [id]) friend_id String friend User @relation(name: "FriendUserFriendships", fields: [friend_id], references: [id]) created_at DateTime @default(now()) updated_at DateTime @updatedAt // 单个唯一约束即可避免重复好友关系(A加B与B加A视为同一记录) @@unique([user_id, friend_id]) }
关键说明
- 给两个关系分别命名为
UserFriendships和FriendUserFriendships,确保名称唯一,避免Prisma混淆关联逻辑 - 在User模型中添加反向数组字段,方便后续查询用户的所有发起/收到的好友关系
- 移除重复的
@@unique([friend_id, user_id]),因为@@unique([user_id, friend_id])已经能阻止同一对用户创建重复的好友关系记录
内容的提问来源于stack exchange,提问作者jakek05
相关产品推荐
相关产品推荐

