Jefsama Jefsama - 7 days ago 5
PHP Question

Laravel 5 eager load a model without relationship

I have..

Models:

Player
id,player_name

Sport
id,sports_name

Game
id,player_id,sports_id,scores


Model Relationship

Player hasMany Games, Sports hasMany Games, Games belongsTo Player and Sports.




Question: In Controller, is it Possible to load Sports and each Games per sports in every Player?

in a single query, i want to achieve in my Blade something like this..

@foreach($player as $p)
@foreach ($p->sport as $ps) /*this wont work, since player has not relationship with sports*/
@foreach ($ps->game as $psg)
{{$psg->id}}
{{$psg->player_name}}
{{$psg->sports_name}}
{{$psg->scores}}
@endforeach
@endforeach
@endforeach


is there other way to achieve it? Thanks!

Answer

You can use Nested eager loading: Player hasMany games, games belongsTo a sport.

$player=Player::with('games','games.sport')->find($id);
foreach($player->games as $game)
{
   echo $game;
   echo $game->sport;
}
Comments