在 Prisma 中无法在一个模型中建立两个 1:1 的关系检测到歧义关系

问题描述

我试图在 prisma ORM 的一个模型中建立两个 1:1 的关系,但出现以下错误

验证模型“人”时出错:检测到不明确的关系。模型 placeOfBirth 中的字段 placeOfDeathPerson 都引用 Place。请通过添加 @relation(<name>) 为它们提供不同的关系名称

我的棱镜模式:

model Place {
    id              Int     @id @default(autoincrement())
    name            String
    persons         Person[]
}

model Person {
    id              Int     @id @default(autoincrement())
    name            String
    placeOfBirthId  Int
    placeOfDeathId  Int
 ? placeOfBirth    Place   @relation(fields: [placeOfBirthId],references: [id])
    placeOfDeath    Place   @relation(fields: [placeOfDeathId],references: [id])
}

完全不明白。

解决方法

您必须将 name 字段添加到 placeOfBirthplaceOfDeath。然后使用这些名称在 Place 模型中引用它们。

model Place {
  id     Int      @id @default(autoincrement())
  name   String
  Births Person[] @relation("Births")
  Deaths Person[] @relation("Deaths")
}

model Person {
  id             Int    @id @default(autoincrement())
  name           String
  placeOfBirthId Int
  placeOfDeathId Int
  placeOfBirth   Place  @relation("Births",fields: [placeOfBirthId],references: [id])
  placeOfDeath   Place  @relation("Deaths",fields: [placeOfDeathId],references: [id])
}