How to make efficient query for $post->commnets and comment->user
Hello, I have a Post model which hasMany Commnets and every comment has one User.
If I run this blade code
@foreach( $post->comments as $comment )
<div>{{ $comment->text }} <br><small>{{ $comment->user->name }}</small></div>
@endforeach
it makes one separate query for user in every loop of the foreach cycle.
I know about Post::with() but this is the third level of relations. Is it possible to have only one query for all users which wrote comments?
Controller code looks like
public function detail(Post $post)
{
return view('home.detail')->with([
'post' => $post
]);
}
Your $post variable is already loaded, so if you can use the load method
public function detail(Post $post)
{
$post->load(['comments', 'comments.user']);
return view('home.detail')->with([
'post' => $post
]);
}
This is it. Thank you Mišo.
Please or to participate in this conversation.