[英]Laravel Eloquent relationship - multiple columns of table reference same foreign key
Laravel/Eloquent 新手在這里。 我正在實現一個簡單的棋盤游戲。 每場比賽有4名玩家。 表結構由一個 Players 表和一個 Games 表組成:
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
目標:我希望能夠獲得玩家參與過的所有游戲。
為此,我嘗試在播放器 model 中編寫 function games()
。 對於 id 2 的玩家,這應該返回游戲 1、3、4 / 對於 id 3 的玩家,它應該返回游戲 1、2、3 等等。
使用原始 SQL 我會做這樣的事情:
SELECT * FROM games WHERE
(player1_id = 2 OR player2_id = 2 OR player3_id = 2 OR player4_id = 2)
但是對於 Eloquent,我很難弄清楚必須如何建立這種關系才能實現這一目標。
同樣,我也希望能夠做相反的事情 - 返回游戲的所有玩家 - 在Game
model 中使用 function players()
。
型號:
// Models/Player.php
//...
class Player extends Model
{
public function games(){
//?
}
}
// Models/Game.php
//...
class Game extends Model
{
public function players(){
//?
}
}
在不更改數據庫結構的情況下,您可能會濫用hasMany
聲明來獲取所有 4 個玩家。
class Game extends Model
{
public function players()
{
return $this->hasMany(Player::class, 'id', 'player1_id')
->orWhere('id', $this->player2_id)
->orWhere('id', $this->player3_id)
->orWhere('id', $this->player4_id);
}
}
class Player extends Model
{
public function games()
{
return $this->hasMany(Game::class, 'player1_id', 'id')
->orWhere('player2_id', $this->id)
->orWhere('player3_id', $this->id)
->orWhere('player4_id', $this->id);
}
}
然而,這並不理想。
您應該有第三張表來正確地 map 這種多對多關系。
table 1 - players: id (pk), name
table 2 - games: id (pk)
table 3 - game_player: id (pk), game_id (fk), player_id (fk), unique([game_id, player_id])
class Game extends Model
{
public function players()
{
return $this->belongsToMany(Player::class, 'game_player');
}
}
class Player extends Model
{
public function games()
{
return $this->belongsToMany(Game::class, 'game_player');
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.