Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Circular reference when loading relations #20006

Closed
nuzkito opened this issue Jul 11, 2017 · 1 comment
Closed

Circular reference when loading relations #20006

nuzkito opened this issue Jul 11, 2017 · 1 comment

Comments

@nuzkito
Copy link

nuzkito commented Jul 11, 2017

  • Laravel Version: 5.4
  • PHP Version: all
  • Database Driver & Version: -

Description:

Suppose a post has many comments

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?

@themsaid
Copy link
Member

For suggestions and feature requests please use the https://github.com/laravel/internals repo.

Thanks :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants