0

I have eager loaded the data but when I am using $object->attribute it again fetch the data from database.

My query is :

$user = User::with([ 'Comment' => function($query){ $query->where('active', 1); $query->with('CommentReply.User'); $query->orderBy('updated_at', 'desc'); } ]);

But when I use $user->comment then it again load all the comments, which results to N+1 problem. Any reason why this is happening? Thanks in advance.

1 Answers1

1

Everything is working fine, just stick to one convention:

$user = User::with([
            'comment' => function($query){
                $query->where('active', 1);
                $query->with('CommentReply.User');
                $query->orderBy('updated_at', 'desc');
            }
]);

//then
$user->comment

or

$user = User::with([
            'Comment' => function($query){
                $query->where('active', 1);
                $query->with('CommentReply.User');
                $query->orderBy('updated_at', 'desc');
            }
]);

//then
$user->Comment

Notice letter casing.

Also mind that $comment->commentReply->user will do just the same, so you need to call $comment->CommentReply->User.

Jarek Tkaczyk
  • 78,987
  • 25
  • 159
  • 157