繁体   English   中英

Laravel通过帖子发表评论

[英]Laravel Pass Comments with Posts

我为具有许多“评论”的“公告”建立了一对多关系。

目前,当我的用户加载应用页面时,我会向其发送30条最新公告,例如:

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

当我通过$ posts对象使用foreach循环回显刀片中的公告时,我还想回显相应帖子下每个帖子的注释。

是否可以将帖子的评论作为实际帖子对象传递? 例如,如果我可以这样做,那就太好了:

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

您可以像这样为评论添加另一个foreach

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

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

@endforeach

@Amr Aly给了您正确的答案,我想补充一点。

当您按他的指示(您应该)循环浏览您的评论时,它将对每个评论进行不同的查询。 因此,如果您有50条评论,那就还有50条查询。

您可以使用急切加载来减轻这种情况

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

然后以他向您展示的方式循环播放。 这会将查询限制为2个。 您可以在以下文档中阅读更多信息: https : //laravel.com/docs/5.4/eloquent-relationships#eager-loading

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM