在Prisma ORM中创建用户与好友自关联多对多关系遇报错求助
Prisma自关联多对多关系配置错误解决办法
你直接定义friends Users[]会报错,核心原因是自关联的多对多关系必须明确双向的关联映射,Prisma无法自动推断单向定义的反向关系逻辑。
以下是两种正确的配置方案:
方案一:隐式中间表(Prisma自动生成)
通过指定统一的relationName关联双向关系,Prisma会自动创建中间表:
model Users { id String @id @unique name String email String password String // 我添加的好友列表 friends Users[] @relation("Friendships", references: [id]) // 把我加为好友的用户列表 friendOf Users[] @relation("Friendships", references: [id]) }
执行prisma migrate dev后,Prisma会自动生成名为UsersFriends的中间表,存储两个用户的关联ID。
方案二:显式中间表(自定义字段)
如果需要在好友关系中添加额外信息(比如申请时间、好友状态),可以手动定义中间模型:
model Users { id String @id @unique name String email String password String friendships Friendship[] } model Friendship { id String @id @unique @default(cuid()) userId String friendId String createdAt DateTime @default(now()) status String // 可取值:"pending"、"accepted"、"rejected" user Users @relation(fields: [userId], references: [id], name: "UserFriendships") friend Users @relation(fields: [friendId], references: [id], name: "FriendOfUser") }
这种方式完全可控,适合需要扩展好友关系属性的场景。
内容的提问来源于stack exchange,提问作者Muhammad Usman
相关产品推荐
相关产品推荐

