Naxon's avatar
Level 6

Team-Game relationship

I'm building a website that involves a schedule of basketball games. I have 2 tables for this: teams and games.

As for the relationships between the models. For Game I got this:

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

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

But what should I do for the Team model? By the games() method inside it, I want to get all the team's games, home and away, and for this I need to reference both home_team and away_team columns on the games table.

My table structure:

teams
-------
id (int, primary)
name (varchar[255])

games
-------
id (int, primary)
home_team (int - references `id` on `teams`)
away_team (int - references `id` on `teams`)
date (datetime)
home_score (int)
away_score(int)
0 likes
4 replies
martinbean's avatar
Level 80

@Naxon You won’t be able to do it with a built-in Eloquent relation, but you could create a method that returns a builder instance:

class Team extends Model
{
    public function games()
    {
        return Game::where('home_team', '=', $this->id)->orWhere('away_team', '=', $this->id);
    }
}

You can then use it like you would a relation:

$games = $team->games()->orderBy('date')->paginate();

Edit: Alternatively, you could add a scope on the Game model to return games for a given team:

class Game extends Model
{
    public function forTeam(Builder $query, Team $team)
    {
        return $query->where(function ($query) use ($team) {
            $query->where('home_team_id', '=', $team->getKey());
            $query->orWhere('away_team_id', '=', $team->getKey());
        });
    }
}
$games = Game::forTeam($team)->orderBy('date')->paginate();
1 like

Please or to participate in this conversation.