Php Laravel用帖子传递评论

Php Laravel用帖子传递评论,php,html,laravel,orm,eloquent,Php,Html,Laravel,Orm,Eloquent,我为我的“公告”建立了一对多的关系,其中有许多“评论” 目前,当我的用户加载应用程序页面时,我让它发送30条最新公告,如: Route::get('/app', function () { $posts = Announcement::take(30)->orderBy('id', 'desc')->get(); return View::make('app')->with([ //posts '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
    ]);
}
当我使用foreach循环通过$posts对象回显blade中的公告时,我还希望回显相应帖子下每个帖子的注释

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

@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

您可以为您的评论添加另一个
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个。你可以从这里的文档中阅读更多内容:

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

当你像他向你展示的那样循环浏览你的评论时(你应该这样做),它会对每个评论进行不同的查询。因此,如果你有50条评论,那就意味着还有50条查询

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

 $posts = Announcement::with('comments')
 ->take(30)->orderBy('id', 'desc')
 ->get();
然后按照他给你的方式循环。这将把查询限制为仅2个。您可以从以下文档中阅读更多内容: