Laravel: whereHas 和 with contains 约束的区别
Laravel: Difference between whereHas and with contains constraint
有什么区别:
->whereHas('user', function($user){
$user->where('age', '>', 21);
})
和
->with(['user' => function($user){
$user->where('age', '>', 21);
}])
除了 with 方法导致预加载之外?
如您所说,With
导致预加载但不会 restrict/filter 结果。
WhereHas
不急于加载用户模型,但 restricts/filters 结果。
想象一个可以有用户或没有用户的博客模型。
WhereHas
将查询用户满足要求的模型,只有 return 个模型符合要求。
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()
会return你
id: 1
user: null
user_id: 1
title: blog post 1
同时
Blog::with(['user' => function($user){
$user->where('age', '>', 21);
}])->get()
会return你
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 岁以上用户的博客文章,并在这些文章上预先加载用户模型,没有限制,因为结果已经受到限制它在 whereHas.
Blog::whereHas('user', function($user){
$user->where('age', '>', 21);
})->with('user');
有什么区别:
->whereHas('user', function($user){
$user->where('age', '>', 21);
})
和
->with(['user' => function($user){
$user->where('age', '>', 21);
}])
除了 with 方法导致预加载之外?
如您所说,With
导致预加载但不会 restrict/filter 结果。
WhereHas
不急于加载用户模型,但 restricts/filters 结果。
想象一个可以有用户或没有用户的博客模型。
WhereHas
将查询用户满足要求的模型,只有 return 个模型符合要求。
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()
会return你
id: 1
user: null
user_id: 1
title: blog post 1
同时
Blog::with(['user' => function($user){
$user->where('age', '>', 21);
}])->get()
会return你
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 岁以上用户的博客文章,并在这些文章上预先加载用户模型,没有限制,因为结果已经受到限制它在 whereHas.
Blog::whereHas('user', function($user){
$user->where('age', '>', 21);
})->with('user');