Laravel /雄辩关系中的多个联接规则

时间:2019-05-07 00:06:38

标签: php sql laravel eloquent

因此,我正在开发一个体育系统,其中games表具有相同表teams的2个关系。我知道上下文通常无关紧要,但是我试图弄清楚为什么用这种方式构造数据库。关系存储为games.home_id references teams.idgames.away_id references teams.id,以链接同一游戏中的两个团队。表结构是

- 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();

谢谢。

1 个答案:

答案 0 :(得分:0)

我认为您可以定义两个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();