在Laravel项目开发中,Eloquent关联查询是非常常用的功能,很多时候我们需要查询主表数据的同时,根据子表的字段条件过滤数据,或者同时过滤主表和子表的数据,这时候就需要掌握正确的关联查询过滤方法。

基础场景说明
假设我们有两个关联的模型,Category(分类,父表)和Product(商品,子表),一个分类下有多个商品,模型关联定义如下:
<?php
namespace AppModels;
use IlluminateDatabaseEloquentModel;
use IlluminateDatabaseEloquentRelationsHasMany;
class Category extends Model
{
// 定义分类和商品的关联
public function products(): HasMany
{
return $this->hasMany(Product::class);
}
}
class Product extends Model
{
// 定义商品所属分类的关联
public function category()
{
return $this->belongsTo(Category::class);
}
}
同时过滤父子表数据的方法
1. 使用whereHas过滤主表,with过滤子表
如果我们想要查询状态为启用的分类,同时过滤出分类下价格大于100的商品,可以使用whereHas过滤主表关联的子表条件,再用with指定子表的过滤条件,避免加载不符合条件的子表数据。
<?php
use AppModelsCategory;
// 查询启用的分类,同时加载价格大于100的商品
$categories = Category::where('status', 1) // 过滤主表(分类)状态为启用
->whereHas('products', function ($query) {
// 过滤子表(商品)价格大于100
$query->where('price', '>', 100);
})
->with(['products' => function ($query) {
// 只加载子表中价格大于100的商品,避免冗余数据
$query->where('price', '>', 100);
}])
->get();
// 遍历结果
foreach ($categories as $category) {
echo "分类名称:{$category->name}" . PHP_EOL;
foreach ($category->products as $product) {
echo "商品名称:{$product->name},价格:{$product->price}" . PHP_EOL;
}
}
2. 使用闭包在with中同时处理父子过滤
如果主表的过滤条件也可以和子表关联起来,也可以把主表条件放到whereHas中,或者直接在with的闭包中处理子表过滤,主表过滤单独写,逻辑更清晰。
<?php
use AppModelsCategory;
// 另一种写法,主表过滤和子表过滤分开
$categories = Category::where('status', 1)
->with(['products' => function ($query) {
$query->where('price', '>', 100)
->where('stock', '>', 0); // 同时过滤子表库存大于0
}])
->get();
注意事项
whereHas的作用是过滤主表数据,只有满足子表条件的主表才会被查询出来,它不会自动过滤子表加载的数据,所以需要配合with的闭包来过滤子表数据。- 如果不需要加载子表数据,只需要过滤主表,可以只使用
whereHas,不需要加with。 - 当关联层级比较深时,比如分类下有商品,商品有订单,可以使用
whereHas的嵌套写法,比如whereHas('products.orders', function ($query) {...})。
常见问题解答
为什么用了whereHas还是会加载所有子表数据?
因为whereHas只负责过滤主表,不会限制子表的加载范围,必须搭配with的闭包条件才能过滤子表数据,避免加载不需要的关联数据。
如何过滤子表不存在的主表数据?
可以使用whereDoesntHave方法,比如查询没有商品的分类:
<?php
use AppModelsCategory;
$categories = Category::whereDoesntHave('products')->get();