Prisma Schema双向外键配置报错及关联关系设置咨询
解决Prisma Schema关联配置报错问题
需求说明
要实现的关联逻辑:
- User模型的
business_id为可选字段,Business模型的owner_id为必填字段 - User → Business:多对一关联(多个用户可归属同一企业)
- Business → User:一对一关联(一个企业仅能有一位所有者)
报错信息
配置后出现以下解析错误:
Error parsing attribute "@relation": The relation fields `Users` on Model `Businesses` and `Businesses` on Model `Users` both provide the `fields` argument in the @relation attribute. You have to provide it only on one of the two fields.
Error parsing attribute "@relation": The relation fields `Users` on Model `Businesses` and `Businesses` on Model `Users` both provide the `references` argument in the @relation attribute. You have to provide it only on one of the two fields.
修正后的Schema配置
model Users { id Int @id @default(autoincrement()) business_id Int? @db.Int // 用户归属企业的多对一关联 business Businesses? @relation(name: "UserBelongsToBusiness", fields: [business_id], references: [id], onUpdate: Cascade, onDelete: Cascade) // 用户作为企业所有者的反向关联 ownedBusinesses Businesses[] @relation(name: "BusinessHasOwner") name String @db.VarChar(255) surname String @db.VarChar(255) email String @unique(map: "email") @db.VarChar(255) password String @db.VarChar(255) } model Businesses { id Int @id @default(autoincrement()) name String @db.VarChar(255) owner_id Int @db.Int // 企业所有者的一对一关联 owner Users @relation(name: "BusinessHasOwner", fields: [owner_id], references: [id], onUpdate: Cascade, onDelete: Cascade) // 归属该企业的用户反向关联 users Users[] @relation(name: "UserBelongsToBusiness") phone String @db.VarChar(255) }
修正说明
- 区分独立关联关系:User与Business之间存在两个不同的关联逻辑,必须给每个关联指定唯一的
name参数,避免Prisma混淆两个关联。 - 遵循Prisma关联规则:每一对关联关系中,仅需在一侧的
@relation中声明fields和references参数,另一侧仅通过关联名称关联即可,解决了报错中"重复指定fields/references"的问题。 - 语义化字段命名:将原有的
Businesses、Users字段名改为更直观的business、owner、users、ownedBusinesses,提升Schema的可读性和维护性。
内容的提问来源于stack exchange,提问作者Illyrian
相关产品推荐
相关产品推荐

