Hi guys, I gave a problem understanding relations...
# orm-help
r
Hi guys, I gave a problem understanding relations. I have a easy example about two users can participate a tennis game. So i have: 1. Model User
Copy code
Model User {
  id      Int @id 
  name    String 
}
2. Model Game
Copy code
Model Game { 
  id        Int @id 
  player1   PlayerInGame
  player2   PlayerInGame
}
3. Model PlayerInGame
Copy code
Model PlayerInGame {
  id      Int @id
  player  User
  game    Game
}
It gives me this error: Error validating model "Game": Ambiguous relation detected. The fields
player2
and
player1
in model
Game
both refer to
PlayerInGame
. Please provide different relation names for them by adding `@relation(<name>). How can i make this work...? Thanks in advance
r
Hey @Roy 👋 \ The best way to perform this would be a many-to-many relation and add two players to the game via this model:
Copy code
model User {
  id    Int    @id
  name  String
  games Game[]
}

model Game {
  id    Int    @id
  name  String
  users User[]
}
r
Thanks @Ryan. But will this also work when i want to add some statistics, like games won, aces etc. ? That will be different per game and user, so that is why I thought about adding PlayerInGame
r
Then something like this should work:
Copy code
model User {
  id          Int            @id
  name        String
  playedGames PlayerInGame[]
}

model Game {
  id    Int            @id
  name  String
  users PlayerInGame[]

}

model PlayerInGame {
  game     Game @relation(fields: [gameId], references: [id])
  player   User @relation(fields: [playerId], references: [id])
  gameId   Int
  playerId Int

  @@id([gameId, playerId])
}
👍 1
r
Thanks for your fast answer. I wil try something like this!
💯 1