预加载不起作用 - Laravel
Eager loading not working - Laravel
我已经急切地加载了数据,但是当我使用 $object->attribute 时,它再次从数据库中获取数据。
我的查询是:
$user = User::with([
'Comment' => function($query){
$query->where('active', 1);
$query->with('CommentReply.User');
$query->orderBy('updated_at', 'desc');
}
]);
但是当我使用 $user->comment 然后它再次加载所有评论,这导致 N+1 问题。发生这种情况的任何原因?提前致谢。
一切正常,只需遵循一个约定:
$user = User::with([
'comment' => function($query){
$query->where('active', 1);
$query->with('CommentReply.User');
$query->orderBy('updated_at', 'desc');
}
]);
//then
$user->comment
或
$user = User::with([
'Comment' => function($query){
$query->where('active', 1);
$query->with('CommentReply.User');
$query->orderBy('updated_at', 'desc');
}
]);
//then
$user->Comment
注意字母大小写。
还要注意 $comment->commentReply->user
也会做同样的事情,所以你需要调用 $comment->CommentReply->User
.
我已经急切地加载了数据,但是当我使用 $object->attribute 时,它再次从数据库中获取数据。
我的查询是:
$user = User::with([
'Comment' => function($query){
$query->where('active', 1);
$query->with('CommentReply.User');
$query->orderBy('updated_at', 'desc');
}
]);
但是当我使用 $user->comment 然后它再次加载所有评论,这导致 N+1 问题。发生这种情况的任何原因?提前致谢。
一切正常,只需遵循一个约定:
$user = User::with([
'comment' => function($query){
$query->where('active', 1);
$query->with('CommentReply.User');
$query->orderBy('updated_at', 'desc');
}
]);
//then
$user->comment
或
$user = User::with([
'Comment' => function($query){
$query->where('active', 1);
$query->with('CommentReply.User');
$query->orderBy('updated_at', 'desc');
}
]);
//then
$user->Comment
注意字母大小写。
还要注意 $comment->commentReply->user
也会做同样的事情,所以你需要调用 $comment->CommentReply->User
.