首页 > 解决方案 > Laravel 6与()的关系

问题描述

我有一个帖子模型,它有很多评论,每条评论都有一个用户模型。如果我跑

@foreach( $post->comments as $comment )
    <div>{{ $comment->text }} <br>{ $comment->user->name }}</div>
@endforeach

它为评论 foreach 中的每个循环向用户生成一个查询。如何编写这段代码,让 Laravel 只对所有用户进行一次查询?

控制器代码看起来像

public function detail(Post $post)
{
    return view('home.detail')->with([
        'post' => $post->with('comments', 'comments.user')->get()->first()
    ]);
}

非常感谢。

标签: eloquentlaravel-6has-many

解决方案


推荐阅读