简体   繁体   English

显示帖子评论的最有效方法

[英]Most Effective way to display comments for a post

Trying to find the best way to display posts from a database with all of their comments. 试图找到显示数据库中所有评论的最佳方式。 I know there has to be a better way but I can't come up with one. 我知道必须有一种更好的方法,但我无法提出一种方法。

In my controller, I am sending to a view the following: 在控制器中,我向视图发送以下内容:

$posts = Post::all();

$comments = Comment::all();

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

In my view I am displaying each post with all of its comments below. 在我看来,我将在下面显示每个帖子及其所有评论。

@foreach($posts as $post)

    {{ $post->content }}

    @foreach($comments as $comment)

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

    @endforeach

@endforeach

Do you have the comments relationship set up in your posts model? 您的帖子模型中是否设置了评论关系?

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

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

And then: 接着:

@foreach($posts as $post)

    {{ $post->content }}

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

@endforeach

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

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