【问题标题】:Laravel eloquent relationship with 2 foreign keysLaravel 雄辩的关系与 2 个外键
【发布时间】:2018-10-15 11:04:30
【问题描述】:

有 2 个表和 2 个模型。表“games”有 2 个外键“team_a_id”和“team_b_id”

我尝试定义关系,但不明白如何建立这种关系。一场比赛只能有一支 A 队和一支 B 队。但一支球队可以有很多场比赛。

此刻我有

class Game extends Model
{
    public function teamA()
    {
        return $this->hasOne('App\Models\Team', 'team_a_id');
    }

    public function teamB()
    {
        return $this->hasOne('App\Models\Team', 'team_b_id');
    }
}

和

class Team extends Model
{
    public function gameTeamA()
    {
        return $this->belongsTo('App\Models\GameSerie', 'team_a_id');
    }

    public function gameTeamB()
    {
        return $this->belongsTo('App\Models\GameSerie', 'team_b_id');
    }
}

我必须定义关系才能找到所有团队为 team_a 或 team_b 的游戏。

例如

$allGames = $team->games($id);

我也不确定我是否正确定义了关系

【问题讨论】:

    标签: laravel-5 eloquent


    【解决方案1】:

    情况正好相反。具有外键的模型具有BelongsTo 关系:

    class Game extends Model
    {
        public function teamA()
        {
            return $this->belongsTo('App\Models\Team', 'team_a_id');
        }
    
        public function teamB()
        {
            return $this->belongsTo('App\Models\Team', 'team_b_id');
        }
    }
    
    class Team extends Model
    {
        public function gameTeamA()
        {
            return $this->hasOne('App\Models\GameSerie', 'team_a_id');
        }
    
        public function gameTeamB()
        {
            return $this->hasOne('App\Models\GameSerie', 'team_b_id');
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-09-29
      • 1970-01-01
      • 2017-05-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-10-12
      相关资源
      最近更新 更多