0

I want to have matches with 2 teams in my App. Currently I implemented this with a simple hasMany/belongsToMany relationship.

Tables: teams, matches, match_team (match_id, team_id)

Team Model

...
public function matches()
{
  return $this->belongsToMany('App\Match');
}

Match Model

...
public function teams()
{
  return $this->belongsToMany('App\Team');
}

So of course I have 2 rows for each match in the Pivot table match_team:

match_id   team_id   
       1      1000
       1      2000
       2      3000
       2      4000

With Blade templating engine I can request f.e. the home team like:

{{$match->teams[0]->name}}

But I want to be more specific and want to have a table like this:

match_id   host_team   guest_team
       1        1000         2000
       2        3000         4000

But then I don't really know how to set those relationships...

Any thoughts/ideas on that? =)

2 Answers2

1

Here is what I suggest: A match can only have two teams, host team and guest team. the trick here is to specify the columns names for the foreign keys (no need for pivot table) Fortunately Laravel offers an easy way to do this. So in your Match model you should add these relationships:

public function hostTeam(){
    return $this->belongsTo('App\Team', 'host_team_id');
}

public function guestTeam(){
    return $this->belongsTo('App\Team', 'guest_team_id');
}

and in the Team model:

public function homeMatches(){
    return $this->hasMany('App\Match', 'host_team_id');
}

public function awayMatches(){
    return $this->hasMany('App\Match', 'guest_team_id');
}

I hope this is was helpful

Mohamed Bouallegue
  • 1,334
  • 15
  • 19
0

Thank you, Mohamed!

Your method works pretty well, but I had to define it like:

public function host()
{
  return $this->hasOne('App\Team', 'id', 'host_id');
}

because a match has only one host team and is not belonging to one.

Anyway, thank you so much! =)