Yanick Schraner Yanick Schraner - 6 months ago 82
MySQL Question

laravel fetch data from table with to foreign keys to the same table

I have two tables:
teams with id, group_id and name
games with id, home_team_id, away_team_id, date and score

As you can see in my games table there are two foreign keys (home_team_id and away_team_id) pointing to the same table (teams).
How can I map those relations with laravel eloquent?
I tried this, but failed:



namespace App;

use Illuminate\Database\Eloquent\Model;

class Team extends Model
{
public function group(){
return $this->belongsTo('App\Group');
}

public function games(){
return $this->hasMany('App\Game');
}
}

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Game extends Model
{
public function homeTeam(){
$this->belongsTo('App\Team', 'home_team_id');
}

public function awayTeam(){
$this->belongsTo('App\Team', 'away_team_id');
}

public function bets(){
$this->hasMany('App\Bet');
}
}


In my view I want to call home_team->name and away_team->name:

<td>{{ $game->homeTeam->name }}</td>
<td>{{ $game->awayTeam->name }}</td>


I get this error:
Relationship method must return an object of type Illuminate\Database\Eloquent\Relations\Relation

and

Relationship method must return an object of type Illuminate\Database\Eloquent\Relations\Relation (View: /home/vagrant/Code/em/resources/views/schedule/index.blade.php)

Answer

You need to return the relationship from the methods. For example:

return $this->belongsTo('App\Team', 'home_team_id');

You do that in your Team model, but not the game model.