I am facing an issue with mapping relations in Laravel Eloquent for two tables: teams and games. The teams table has id, group_id, and name fields, while the games table includes id, home_team_id, away_team_id, date, and score. The problem arises from the fact that both foreign keys (home_team_id and away_team_id) in the games table are pointing to the same table (teams). I attempted to map these relations using Laravel Eloquent but encountered a failure.
Here is a snippet of my code:
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');
}
}
When trying to access home_team->name and away_team->name in my view file, I encounter the following error:
<td>{{ $game->homeTeam->name }}</td>
<td>{{ $game->awayTeam->name }}</td>
The error message reads: "Relationship method must return an object of type Illuminate\Database\Eloquent\Relations\Relation."