Laravel雄辩的关系与2个外键

时间:2018-10-15 11:04:30

标签: laravel-5 eloquent

有2个表和2个模型。表“游戏”具有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是team_a或team_b的所有游戏。

例如

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

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

1 个答案:

答案 0 :(得分: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');
    }
}