【问题标题】:Laravel Pass Comments with PostsLaravel 通过帖子评论
【发布时间】:2017-07-29 19:24:56
【问题描述】:

我为具有许多“cmets”的“公告”设置了一对多关系。

目前,当我的用户加载应用页面时,我让它发送 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 循环在刀片中回显公告时,我还想在相应帖子下回显每个帖子的 cmets。

是否可以将帖子的 cmets 作为实际帖子对象的一部分传递?例如,如果我能这样做就好了:

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

【问题讨论】:

    标签: php html laravel orm eloquent


    【解决方案1】:

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

    当您按照他向您展示的那样(并且您应该)循环浏览您的 cmets 时,它会对每条评论进行不同的查询。所以如果你有 50 个 cmets,那就是 50 个查询。

    您可以通过使用急切加载来缓解这种情况

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

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

    【讨论】:

      【解决方案2】:

      您可以为您的评论添加另一个foreach,如下所示:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2014-05-10
        • 2016-09-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-05-14
        • 1970-01-01
        相关资源
        最近更新 更多