传递两个不同的查询时出错导致在PHP中查看

时间:2017-10-14 17:41:48

标签: php laravel

我正在从事小编程工作,我希望在其中展示图像及其相关评论,如Facebook。

我的图片在一张桌子中,并在一张桌子上发表评论。我从不同的表中获取它们,我想将这些结果传递给查看。在那里,我想根据其相关帖子显示这些结果。但这给了我错误。每条评论都有相关的post_id,实际上是帖子的post_id

这是我的代码。

型号:

public function load_posts_with_comments(){
    $posts    = image_post::all(); // loading all posts
    $comments = commenting::all(); // loading all comments
    return view('home_page_of_posts', [
        'posts'    => $posts,
        'comments' => $comments
    ]); // passing it to view, there I will do it through for each nested loop but it does not work.
}

1 个答案:

答案 0 :(得分:3)

如果帖子和评论模型尚不存在,请在帖子和评论模型之间建立hasMany关系。有些人喜欢:

public function comments()
{
    return $this->hasMany(Comment::class);
}

然后使用with()方法加载与每个帖子相关的评论。这样的事情会起作用:

public function loadPostsWithComments()
{
    $posts = Post::with('comments')->get();

    return view('home_page_of_posts', compact('posts'));
}

然后在Blade模板中,您可以迭代帖子和评论:

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