vendredi 4 août 2017

Laravel Eager loading internal constraints are not limited if followed by nested 'with'

This is a question and my own answer (solution I figured out by chance). Laravel documentation does not mention this and it brought me hours of programming suffering.

Let's say we have Posts with Comments and Votes (for comments). Laravel's favorite example. Models and relationships are Textbook (from Laravel's docs). Posts have comments, comments have votes.

So,

$comments_ids = [1,6,7,22];

Post::where('id', $post_id)
            ->with(['comments' =>  function($query) use ($comments_ids) {
                $query->whereIn('id', $comments_ids);
            }])
            ->with('comments.votes')
            ->first();

So, I should expect Post with comments which, ids are 1,6,7,22 and votes eager loaded.

But not so fast! I get ALL COMMENTS! ALL OF THEM! ...why?



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/2voFyAy
via IFTTT

Aucun commentaire:

Enregistrer un commentaire