[英]Multiple join rules in Laravel/Eloquent relation
所以,我正在开发一个体育系统,其中games
桌有两个关系用于同一桌面teams
。 我知道上下文通常并不重要,但我试图弄清楚为什么数据库被这样结构化了。 关系存储为games.home_id references teams.id
和games.away_id references teams.id
来链接同一游戏中的2个团队。 表结构是
- games
- id
- home_id
- away_id
- starts_at
- teams
- id
- team_players
- id
- team_id
所以,如果我想让今天所有的比赛球员参加比赛,我会做的
SELECT team_players.*
FROM team_players
JOIN teams ON (teams.team_id = team_players.team_id)
JOIN games ON (teams.id = games.home_id OR teams.id = games.away_id)
WHERE games.starts_at <= $starts AND games.starts_at >= $ends
如何在模型中创建hasMany
关系以包含两者(team.id = games.home_id OR team.id = games.away_id)
?
我已经尝试过类似的东西
class Team {
public function game()
{
return $this->hasMany(Game::class);
}
}
class Game {
public function teams()
{
$rel = $this->hasMany(Game::class, 'home_id');
$rel->orHasMany(Game::class, 'home_id');
return $rel;
}
}
但是没有orHasMany()
;
谢谢。
我认为你可以定义两个has-many-through
关系并合并它们,它没有经过测试,但我认为它可以是你的解决方案,请测试它并让我知道,你也可能需要改变一下钥匙,我刚写的给你一些想法
class Game extends Model
{
public function homeTeamPlayers()
{
return $this->hasManyThrough(
'App\TeamPlayer',
'App\Team',
'id', // Foreign key on teams table...
'team_id', // Foreign key on team_players table...
'home_id', // Local key on games table...
'id' // Local key on teams table...
);
}
public function awayTeamPlayers()
{
return $this->hasManyThrough(
'App\TeamPlayer',
'App\Team',
'id', // Foreign key on teams table...
'team_id', // Foreign key on team_players table...
'away_id', // Local key on games table...
'id' // Local key on teams table...
);
}
public function teamPlayers()
{
$this->homeTeamPlayers->merge($this->awayTeamPlayers);
}
}
现在,对于你可以检索的每一款游戏
$game = Game::find(1);
$game->teamPlayers();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.