2017-03-09 97 views
0

我有一個一對多的關係,爲我的「公告」設置了許多「評論」。Laravel Pass對帖子的評論

目前,當我的用戶負荷高達應用程序頁面,我把它送30個最近宣佈像這樣:

Route::get('/app', function() { 
    $posts =  Announcement::take(30)->orderBy('id', 'desc')->get(); 
    return View::make('app')->with([ 
     //posts 
     'posts'  => $posts, 
     //orders 
     'orders'  => $orders 
    ]); 
} 

當我回聲出使用foreach循環通過$帖子在葉片上的公告對象,我還想在各自的帖子中回覆每篇文章的評論。

是否可以將帖子的評論作爲實際帖子對象的一部分傳遞給該帖子?例如,這將是很好,如果我能做到這一點:

@foreach ($posts as $post) 
    //echo out the post 
    {{$post->content}} 
    //echo out the comments relating to this post 
    {{$post->comments}} 
@endforeach 

回答

1

@Amr阿里給你正確的答案,我會喜歡加在它上面。

當您循環顯示您的評論(並且您應該)時,它會對每條評論做出不同的查詢。如果你有50條評論,那麼還有50條查詢。

您可以通過使用預先加載

$posts = Announcement::with('comments') 
->take(30)->orderBy('id', 'desc') 
->get(); 

然後,只需循環的方式,他展示了減輕。這將僅限於查詢2。您可以在這裏閱讀更多文檔:https://laravel.com/docs/5.4/eloquent-relationships#eager-loading

1

您可以添加其他foreach像這樣的評論:

@foreach ($posts as $post) 
     //echo out the post 

     @if($post->comments->count()) 
      @foreach ($post->comments as $comment) 
      // {{ $comment }} 
      @endforeach 
     @endif 

@endforeach