Laravel/Eloquent newbie here. I am implementing a simple board game. Each game has 4 players. The tables structure consists of a Players table and a Games table:
SELECT * FROM players;
id | name |
---------------------
1 | John |
2 | Mary |
3 | Linda |
4 | Alex |
5 | Chris |
6 | Ron |
7 | Dave |
SELECT * FROM games;
id | player1_id | player2_id | player3_id player4_id
---------------------------------------------------------------------
1 | 1 | 2 | 3 | 4
2 | 3 | 5 | 6 | 7
3 | 2 | 3 | 5 | 6
4 | 2 | 4 | 5 | 7
Goal: I want to be able to get all games a player has participated in.
For this I am trying to write a function games()
in the Player model. For player with id 2 this should return games 1, 3, 4 / for player with id 3 it should return games 1, 2, 3 and so forth.
With raw SQL I would do something like this:
SELECT * FROM games WHERE
(player1_id = 2 OR player2_id = 2 OR player3_id = 2 OR player4_id = 2)
But with Eloquent I'm having a hard time figuring out how one must set up this relationship to achieve this.
Equivalently I'd also like to be able to do the opposite - to return all players of a game - with a function players()
in the Game
model.
The models:
// Models/Player.php
//...
class Player extends Model
{
public function games(){
//?
}
}
// Models/Game.php
//...
class Game extends Model
{
public function players(){
//?
}
}