lundi 15 octobre 2018

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



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire