2015-12-03 67 views
0

试图找到从数据库中显示帖子及其所有评论的最佳方式。我知道必须有更好的方式,但我不能拿出一个。显示帖子评论的最有效方式

在我的控制,我发送到视图:

$posts = Post::all(); 

$comments = Comment::all(); 

return view('layouts.main',compact('posts,comments')); 

在我看来,我显示每个岗位与所有的低于其意见。

@foreach($posts as $post) 

    {{ $post->content }} 

    @foreach($comments as $comment) 

     @if($comment->post->id == $post->id) 
      {{ $comment->content }} 
     @endif 

    @endforeach 

@endforeach 

回答

1

您是否在您的帖子模型中设置了评论关系?

$posts = Post::with('comments')->all(); 

return view('layouts.main',compact('posts')); 

然后:

@foreach($posts as $post) 

    {{ $post->content }} 

    @foreach($post->comments as $comment) 
      {{ $comment->content }} 
    @endforeach 

@endforeach 
相关问题