Jefsama
Jefsama

Reputation: 553

Laravel 5 eager load a model without direct 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!

Upvotes: 2

Views: 1470

Answers (2)

Amit Gupta
Amit Gupta

Reputation: 17658

The relation between Player and Sport is also the many-to-many.

So you can define a sports relation in Player model as:

public function sports()
{
  return $this->belongsToMany('App\Sport', 'games')->withPivot('scores');
}

Then in your view you can write your foreach as:

@foreach($player as $p)
  @foreach ($p->sports as $s)
      {{$p->player_name}}
      {{$s->sports_name}}
      {{$s->pivot->scores}}
  @endforeach
@endforeach

Upvotes: 1

Sanzeeb Aryal
Sanzeeb Aryal

Reputation: 3266

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;
}

Upvotes: 2

Related Questions