【问题标题】:Multiple join rules in Laravel/Eloquent relationLaravel/Eloquent 关系中的多个连接规则
【发布时间】:2019-09-24 14:23:37
【问题描述】:

所以,我正在开发一个运动系统,其中games 表与同一张表teams 有两个关系。我知道上下文通常无关紧要,但我试图弄清楚为什么数据库是以这种方式构建的。关系存储为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()

谢谢。

【问题讨论】:

    标签: php sql laravel eloquent


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-01-05
      • 1970-01-01
      • 1970-01-01
      • 2019-06-23
      • 1970-01-01
      • 1970-01-01
      • 2016-07-22
      相关资源
      最近更新 更多