2016-11-28 44 views
2

我有一個模型..Laravel 5急於負荷沒有直接關係

模式

Player 
id,player_name 

Sport 
id,sports_name 

Game 
id,player_id,sports_id,scores 

模型關係

球員的hasMany遊戲運動小號的hasMany遊戲遊戲屬於關聯球員體育


問題:控制器,是可能加載體育每個遊戲每體育在每個球員

在一個查詢

,我想在我的刀片像這樣實現..

@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:玩家有許多遊戲,遊戲屬於一項運動。

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

PlayerSport之間的關係也是many-to-many

所以,你可以在Player模型定義sports關係:

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