Relation two to many with Prisma

Viewed 56

I'm trying to create a prisma schema with this kind of relation - I have two models: Player and Game. Every game is "played" by two players and I'm trying to connect them with something like this:

model Player {
    id                  String @id @default(cuid())
    name                String
    games               Game[] 
}

model Game {
    id                  Int @id @default(autoincrement())
    player_1            Player
    player_2            Player
    winnerId            String
}

In this case I get an error which says Ambiguous relation detected. The fields player_1 and player_2 in model Game both refer to Player. Please provide different relation names for them by adding @relation(<name>).

And if I add relation with names which looks like this:

player_1            Player @relation(name: "GamePlayer1")
player_2            Player @relation(name: "GamePlayer2")

I get an error The relation field player_1/player_2 on Model Game is missing an opposite relation field on the model Player. I don't think that adding additional fields to Player model is necessary and also don't think that adding many to many relation which would look like this players: Player[] is smart.

What would be the right way to connect those two models based on my example?

1 Answers

You need to provide both player's id on Game and separate relation name on Player and Game. Here the right way to fix it:

model Player {
  id             String @id @default(cuid())
  name           String
  games_player_1 Game[] @relation(name: "GamePlayer1")
  games_player_2 Game[] @relation(name: "GamePlayer2")
}

model Game {
  id          Int    @id @default(autoincrement())
  player_1_id String
  player_2_id String
  player_1    Player @relation(name: "GamePlayer1", fields: [player_1_id], references: [id], onDelete: Cascade)
  player_2    Player @relation(name: "GamePlayer2", fields: [player_2_id], references: [id], onDelete: Cascade)
  winnerId    String
}

Related