繁体   English   中英

棱镜中的多对一

[英]Many to one in prisma

是否可以将两个或多个场与棱镜中的单个矩阵相关联?

我正在尝试这个:

model Match {
  id            String @id @default(uuid())
  tournament_id String
  team_one_id   String
  team_two_id   String

  tournament Tournament? @relation(fields: [tournament_id], references: [id])
  team_one   Team        @relation(fields: [team_one_id], references: [id])
  team_two   Team        @relation(fields: [team_two_id], references: [id])

  @@map("matches")
}

model Team {
  id       String @id @default(uuid())
  owner_id String
  matches Match[]

  @@map("teams")
}

但我收到以下错误: 错误

如果 model 上的两个字段是引用相同 model(在本例中为Team )的关系字段,则需要证明@relationname参数。

文档: https://www.prisma.io/docs/reference/api-reference/prisma-schema-reference#relation

在您的架构中,您需要像这样指定关系的名称:

model Match {
  id            String @id @default(uuid())
  tournament_id String
  team_one_id   String
  team_two_id   String

  tournament Tournament? @relation(fields: [tournament_id], references: [id])
  team_one   Team        @relation(fields: [team_one_id], references: [id], name: "matches_team_one")
  team_two   Team        @relation(fields: [team_two_id], references: [id], name: "matches_team_two")

  @@map("matches")
}

model Team {
  id       String @id @default(uuid())
  owner_id String
  matchesTeamOne Match[] @relation(name: "matches_team_one")
  matchesTeamTwo Match[] @relation(name: "matches_team_two")

  @@map("teams")
}

这实际上在规模上不起作用,因为您需要在MatchTeam model 上定义两个单独的关系字段。为什么不将 teams 字段定义为Match上的数组,这样您只需要执行一次?

model Match {
  id            String @id @default(uuid())
  tournament_id String
  team_one_id   String
  team_two_id   String

  tournament Tournament? @relation(fields: [tournament_id], references: [id])
  teams Team[]

  @@map("matches")
}

model Team {
  id       String @id @default(uuid())
  owner_id String
  matches  Match[]

  @@map("teams")
}

此解决方案的警告是您必须在后端级别验证teams字段只有 2 个连接的团队,不多也不少。 但它使这种关系对开发人员更加透明,并且更容易在后台进行管理。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM