Laravel 5急切地加载一个没有直接关系的模型

时间:2016-11-28 10:26:26

标签: php laravel eloquent laravel-5.2

我有..

模型

Player
id,player_name

Sport
id,sports_name

Game
id,player_id,sports_id,scores

模型关系

播放器 hasMany 游戏体育 hasMany 游戏游戏 属于 播放器体育

问题:在控制器中,是否可能在每个运动中加载体育和每个游戏 < EM>播放器的

在一个查询中,我希望在我的 Blade 中实现这样的目标..

@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

还有其他方法可以实现吗?谢谢!

2 个答案:

答案 0 :(得分:2)

你可以使用Nested eager loading:玩家拥有许多游戏,游戏属于运动。

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

答案 1 :(得分:1)

PlayerSport之间的关系也是many-to-many

因此,您可以在sports模型中将Player关系定义为:

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

然后在您看来,您可以将foreach写为:

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