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

在Prisma中能否将多个字段关联至单个模型?附关联报错求助

Prisma中关联多个字段到单个模型的解决方案

可以实现,你遇到的错误是因为Prisma无法区分Team模型中指向Match的两个反向关系(作为team_one和team_two的比赛)。需要给每个@relation指定唯一名称,同时在Team模型中定义对应的反向关系字段。

修改后的模型代码:

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(name: "TeamOneMatches", fields: [team_one_id], references: [id])
  team_two   Team        @relation(name: "TeamTwoMatches", fields: [team_two_id], references: [id])

  @@map("matches")
}

model Team {
  id       String @id @default(uuid())
  owner_id String
  // 对应Match中的team_one反向关系
  teamOneMatches Match[] @relation(name: "TeamOneMatches")
  // 对应Match中的team_two反向关系
  teamTwoMatches Match[] @relation(name: "TeamTwoMatches")

  @@map("teams")
}

关键说明:

  • 给Match里的每个Team关联添加name参数,确保两个关系名称唯一(比如"TeamOneMatches"和"TeamTwoMatches")
  • 在Team模型中创建两个对应的反向关系字段,字段名可自定义,但必须和Match中@relation的name参数完全匹配
  • 这样Prisma就能明确区分每个关联的方向,解决报错问题

内容的提问来源于stack exchange,提问作者Sasuke

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 07:25:18