【发布时间】:2022-10-18 14:18:29
【问题描述】:
有什么区别:
->whereHas('user', function($user){
$user->where('age', '>', 21);
})
和
->with(['user' => function($user){
$user->where('age', '>', 21);
}])
除了 with 方法会导致急切加载吗?
【问题讨论】:
有什么区别:
->whereHas('user', function($user){
$user->where('age', '>', 21);
})
和
->with(['user' => function($user){
$user->where('age', '>', 21);
}])
除了 with 方法会导致急切加载吗?
【问题讨论】:
正如您所说,With 会导致急切加载,但不会限制/过滤结果。
WhereHas 不会急切加载用户模型,而是限制/过滤结果。
想象一个可以有或没有用户的博客模型。
WhereHas 将查询用户满足要求的模型,并且只返回满足要求的模型。
With 将查询所有博客模型,但仅在满足要求时才包括用户。
三篇博文
id: 1
user: { id: 1, age: 25 }
title: blog post 1
id: 2
user: null
title: blog post two without user
id: 3
user: { id: 3, age: 15 }
title: blog post 2 with user low age
这个
Blog::whereHas('user', function($user){
$user->where('age', '>', 21);
})->get()
会还给你
id: 1
user: null
user_id: 1
title: blog post 1
尽管
Blog::with(['user' => function($user){
$user->where('age', '>', 21);
}])->get()
会还给你
id: 1
user: { id: 1, age: 25 }
user_id: 1
title: blog post 1
id: 2
user: null
user_id: null
title: blog post 2 without user
id: 3
user: null
user_id: 3
title: blog post 2 with user low age
您很可能会像这样将两者一起使用,仅限于获取 21 岁以上用户的博客文章,并急切地在这些文章上加载用户模型,因为结果已经在 @987654330 中受到限制@
Blog::whereHas('user', function($user){
$user->where('age', '>', 21);
})->with('user')->get();
【讨论】: