我有..
模型:
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
还有其他方法可以实现吗?谢谢!
答案 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)
Player
和Sport
之间的关系也是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