Viktor
Viktor

Reputation: 1702

Laravel eloquent relationship with 2 foreign keys

There are 2 tables and 2 models. Table "games" has 2 foreign keys "team_a_id" and "team_b_id"

I try to define relationship but can't understand how build this relationship. One game can have only one team A and only one team B. But one team can have many games.

At this moment I have

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');
    }
}

and

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');
    }
}

I have to define relationship in order to find all games where team was team_a or team_b.

e.g.

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

Also i am not sure that i defined relationships right

Upvotes: 1

Views: 271

Answers (1)

Jonas Staudenmeir
Jonas Staudenmeir

Reputation: 25936

It's the other way around. The model with the foreign key has the BelongsTo relationship:

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');
    }
}

Upvotes: 1

Related Questions