2017-03-09 49 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