mardi 20 octobre 2015

Laravel 5.1 Eloquent Relationship for a table with two user id columns

I've got a sports app that has a list of Competitors (competitors table) and a Match (matches table) where in a match there are two competitors so the matches table has a column for player with hasOne competitor relationship, and another column for opponent with hasOne competitor relationship, which seems okay as the relationships for the Match model looks like this:

Match Model

public function player()
{
    return $this->hasOne('App\Competitor');
}

public function opponent()
{
    return $this->hasOne('App\Competitor');
}

Now I'm confused though when looking at the Competitors model, which originally I thought might look like this:

Competitors Model

public function match()
{
    return $this->belongsTo('App\Match');
}

But that's not going to map to either player or competitor when I want to just get the different matches the competitor is in.

Is the only way to overcome this by setting the column name specifically and setting up two belongsTo relationships like this and then just merge the results:

public function playerMatch()
{
    return $this->belongsTo('App\Match', 'player_id');
}

public function opponentMatch()
{
    return $this->belongsTo('App\Match', 'opponent_id');
}

Or is there a way to setup something like original example with match, but get a union of results with some sort of Laravel magic?



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire