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

如何在Prisma中创建Friendship模型?关联名称重复报错求助

解决Prisma中Friendship模型的关系命名冲突问题

在开发类Facebook应用时,构建Friendship模型遇到Prisma验证错误:

Error validating model "Friendship": Wrongly named relation detected. The fields user and friend in model Friendship both 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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.18 04:30:11