2016-11-28 15 views
2

..Laravel 5熱心な負荷モデル

モデル

Player 
id,player_name 

Sport 
id,sports_name 

Game 
id,player_id,sports_id,scores 

モデルの関係

プレーヤーhasManyのゲームスポーツShasManyのゲームゲームbelongsToのプレーヤースポーツ


質問:コントローラでは、それはすべてのプレーヤーのスポーツあたりスポーツと各ゲームをロードするためにことは可能ですか?単一のクエリで

、私はこのように私のブレード何かに達成したい...

@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 

それを達成するための他の方法がありますか?ありがとう!

+1

あなたは試したことがあり、多くのトラフ関係を持っていますか? https://laravel.com/docs/5.2/eloquent-relationships#has-many-through – TheFallen

答えて

2

あなたはNested eager loadingを使用することができます:プレーヤーhasManyゲーム、games belongsToスポーツ。

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

PlayerSport関係もmany-to-manyあります。

だから、としてPlayerモデルでsports関係を定義することができます。その後、あなたのビューであなたのようにあなたのforeachを書くことができ

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

@foreach($player as $p) 
    @foreach ($p->sports as $s) 
     {{$p->player_name}} 
     {{$s->sports_name}} 
     {{$s->pivot->scores}} 
    @endforeach 
@endforeach 
関連する問題