Home > Mobile >  Laravel Relation for Triple ID
Laravel Relation for Triple ID

Time:02-24

I got three tables, and one matching table.

tournaments, seasons, teams

and

seasons_tournaments_teams

table.

And I had another table named 'games' and I put 'season_tournament_team_id' to that table.

So that, I want to write a relation to get Team of the game. (And It will be always only one)

public function team(): \Illuminate\Database\Eloquent\Relations\BelongsTo
{
    return $this->belongsTo('App\Models\Team');
}
public function season(): \Illuminate\Database\Eloquent\Relations\BelongsTo
{
    return $this->belongsTo('App\Models\Team');
}
public function tournament(): \Illuminate\Database\Eloquent\Relations\BelongsTo
{
    return $this->belongsTo('App\Models\Team');
}

The code above is not correct of course. But I need to learn that, how can I reach to the team, season and tournament by game model?

CodePudding user response:

And I had another table named 'games' and I put 'season_tournament_team_id' to that table.

You can make a belongsTo relationship to that model then.

# Game model
public function season_tournament_team()
{
    return $this->belongsTo(SeasonTournamentTeam::class, 'season_tournament_id');
}

The relationships you defined in the SeasonTournamentTeam model are also belongsTo, so you could access it like that.

$game = Game::find(/*some-id*/);

$team = $game->season_tournament_team->team;
$season = $game->season_tournament_team->season;
$tournament = $game->season_tournament_team->tournament;

If it's a single game, not eager loading is fine. The amount of queries will remain the same.

If you are querying multiple games, then you should eager load the relationships.

$games = Game::with([
        'season_tornament_team.team',
        'season_tornament_team.season',
        'season_tornament_team.tournament',
    ])
    ->get();

foreach ($games as $game) {
    $team = $game->season_tournament_team->team;
    $season = $game->season_tournament_team->season;
    $tournament = $game->season_tournament_team->tournament;
}
  • Related