我在理解 Prisma 中的关系和数据建模时遇到问题。我有一个关于两个可以参加网球比赛的用户的“简单”示例。所以我有:
Model User {
id Int @id
name String
}
Model Game {
id Int @id
player1 PlayerInGame
player2 PlayerInGame
}
Model PlayerInGame {
id Int @id
player User
game Game
}
它给了我这个错误:
Error validating model "Game": Ambiguous relation detected. The fields `player1` and `player2` in model `Game` both refer to `PlayerInGame`. Please provide different relation names for them by adding `@relation(<name>).
我该如何解决这个问题? 预先感谢。
我也尝试在 @relation 字段,但这给了我以下错误:
model Game {
id Int @id @default(autoincrement())
createdAt DateTime @default(now())
player1 PlayerInGame @relation("player1")
player2 PlayerInGame @relation("player2")
}
Error validating model "Game": Automatic related field generation would cause a naming conflict. Please add an explicit opposite relation field.
您可以通过在
PlayerInGame
上提供两个关系字段来修复此错误。您在 Game
上有两个关系字段。因此,您还需要 PlayerInGame
上的两个相反的关系字段。在您的应用程序逻辑中,您必须确保仅设置这两个关系字段之一。所以只需根据您的业务领域设置PlayerInGame.gameAsPlayer1
或PlayerInGame.gameAsPlayer2
即可。
model User {
id Int @id
name String
}
model Game {
id Int @id
player1 PlayerInGame @relation("GamePlayer1")
player2 PlayerInGame @relation("GamePlayer2")
}
model PlayerInGame {
id Int @id
player User
gameAsPlayer1 Game? @relation("GamePlayer1")
gameAsPlayer2 Game? @relation("GamePlayer2")
}
最好的方法是建立多对多关系。您将来也可以向游戏添加任意数量的用户,并且可以依次扩展。
model User {
id Int @id
name String
games Game[]
}
model Game {
id Int @id
name String
users User[]
}
然后您可以有条件地检查游戏中的玩家数量,并在您的业务逻辑中对其进行限制。
就我而言,由于同一个表中的多个字段中使用了 FK,我遇到了此问题。每当您与模型有超过 1 个关系时,您需要提供一个关系名称来消除关系的歧义。
示例:
model User {
id Int @id
name String
games Game[]
}
model Game {
game_id Int @id
name String
users User[]
}
model PlayerInGame {
id Int @id
player User
gameAsPlayer1 Game? @relation("GamePlayer1", fields: [gameAsPlayer1Id], references: [game_id])
gameAsPlayer1Id Int
gameAsPlayer2 Game? @relation("GamePlayer2", fields: [gameAsPlayer2Id], references: [game_id])
gameAsPlayer2Id Int
}