Home » Php » Eloquent: Two foreign keys in a table pointing to the same table

Eloquent: Two foreign keys in a table pointing to the same table

Posted by: admin October 26, 2017 Leave a comment

Questions:

I have two models:

  • Team
  • Game (Played between two games)

The Game model has two foreign keys pointing to the Team model – team1_id & team2_id.

Here’s the code for Team model:

class Team extends Eloquent
{
    protected $table = 'team';

    protected $fillable = [
        'name',
        'color',
        'year'
    ];

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

Code for Game model:

class Game extends Eloquent
{
    protected $table = 'game';

    protected $casts = [
        'team1_id' => 'int',
        'team2_id' => 'int'
    ];

    protected $fillable = [
        'team1_id',
        'team2_id',
        'location',
        'start_at'
    ];

    public function team1()
    {
        return $this->hasOne(\App\Models\Team::class, 'team1_id');
    }

    public function team2()
    {
        return $this->hasOne(\App\Models\Team::class, 'team2_id');
    }
}

I get an error saying the column could not be found.

return $this->hasMany(\App\Models\Game::class, 'team1_id');

This works, but the problem is that I want to get games depending on both team1_id and team2_id.

Answers: