You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
class Post extends Model
{
public function comments()
{
return $this->hasMany(Comment::class);
}
}
and a comment belongs to a post
class Comment extends Model
{
public function post()
{
return $this->belongsTo(Post::class);
}
}
You can get a post with comments doing
$post = Post::with('comments')->find($id);
but then, if you iterate comments and use the post of the comment,
// Example. Suppose that this can be more complex and you can't simply pass $post to doSomenthingWithComment.
function doSomethingWithComment($comment) {
chechkSomePostCondition($comment->post);
}
foreach ($post->comments as $comment) {
doSomenthingWithComment($comment);
}
Eloquent will make a new query to the database for each $comment->post
select * from `posts` where `posts`.`id` = '33' limit 1;
select * from `posts` where `posts`.`id` = '33' limit 1;
select * from `posts` where `posts`.`id` = '33' limit 1;
...
But $comment->post is the same post that $post.
To avoid multiple queries you can do
$post = Post::with('comments.post')->find($id);
but this still creates an extra query
select * from `posts` where `id` = '33' limit 1; -- Query from Post::find.
select * from `posts` where `posts`.`id` in ('33'); -- Query from eager loading.
Is it possible for posts and comments to have a circular reference between them to avoid the second query? In this example you can simulate it doing
foreach ($post->comments as $comment) {
$comment->post()->associate($post);
}
but can be this done with Eloquent directly?
The text was updated successfully, but these errors were encountered:
Description:
Suppose a post has many comments
and a comment belongs to a post
You can get a post with comments doing
but then, if you iterate comments and use the post of the comment,
Eloquent will make a new query to the database for each
$comment->post
But
$comment->post
is the same post that$post
.To avoid multiple queries you can do
but this still creates an extra query
Is it possible for posts and comments to have a circular reference between them to avoid the second query? In this example you can simulate it doing
but can be this done with Eloquent directly?
The text was updated successfully, but these errors were encountered: