嵌套 with() 调用会覆盖闭包条件,导致 active = false 记录混入;应统一在 scopeWithActiveSubscriptions 中注册所有关系并合并约束,避免多次 with() 拆分调用。

嵌套 with() 调用会覆盖作用域里的闭包条件
直接链式调用 withActiveSubscriptions() 和 with('subscriptions.plan') 会导致前者定义的 where('active', true) 失效——Eloquent 把第二次 with() 当作全新加载指令,不再复用之前的闭包约束。
现象是:$user->subscriptions 里混入了 active = false 的记录,但 plan 关系却能正常加载。这不是数据错乱,而是预加载逻辑被拆分后失去上下文。
- 根本原因:Eloquent 不合并重复关系的约束,
subscriptions被注册了两次(一次带闭包,一次无闭包) - 验证方式:开启查询日志,你会看到两条独立的
SELECT * FROM subscriptions WHERE user_id = ?,其中一条没带AND active = 1 - 兼容性影响:该问题在 Laravel 8+ 全版本存在,不是 bug,是设计机制
必须把嵌套关系一次性传进作用域参数
正确做法是让 scopeWithActiveSubscriptions() 接收完整路径数组,内部用 array_merge() 统一注册所有关系,确保 subscriptions 的基础过滤始终生效,其他嵌套只是补充。
示例写法:
public function scopeWithActiveSubscriptions($query, array $nestedRelations = [])
{
$relations = [
'subscriptions' => function ($q) {
$q->where('active', true);
}
];
<pre class="brush:php;toolbar:false;">foreach ($nestedRelations as $relation => $constraint) {
if (is_string($relation)) {
$relations[$relation] = $constraint;
} else {
$relations[$constraint] = null;
}
}
return $query->with($relations);}
- 调用时写成
->withActiveSubscriptions(['subscriptions.plan']),不是分开两次with() - 支持带条件的嵌套:
->withActiveSubscriptions(['subscriptions.plan' => function ($q) { $q->where('type', 'GOLD'); }]) - 若需多层如
subscriptions.plan.features,也必须作为字符串完整传入,不能拆成['subscriptions.plan', 'plan.features']
whereHas + 带闭包的 with 才能保层级结构
当你要按最底层数据(比如 Product 名称)反向拉取完整树形结构(Category → Subcategory → Product),单靠作用域不够,得组合 whereHas() 过滤和 with() 约束预加载。
关键点在于:每层都用 whereHas() 缩小父级范围,再用带闭包的 with() 控制子级内容,避免空节点。
-
Category::whereHas('subcategories.products', fn ($q) => $q->where('name', 'like', "%{$search}%"))—— 先筛出含匹配产品的分类 -
->with(['subcategories' => fn ($q) => $q->whereHas('products', fn ($q2) => $q2->where('name', 'like', "%{$search}%"))])—— 只加载含匹配产品的子分类 -
->with(['subcategories.products' => fn ($q) => $q->where('name', 'like', "%{$search}%")])—— 子分类下只预加载匹配的产品 - 漏掉任一环节,返回结果中就会出现“有分类但子分类为空”或“子分类有但产品全不匹配”的脏数据
多属性交集过滤别用单个 whereHas
对一对多关联(如 Product → Attribute)做“颜色=黑 且 灵敏度=1800 DPI”这类交集筛选,绝不能在一个 whereHas('attributes', ...) 里写多个 whereIn。
那样查出来的是「满足任一属性」的商品,因为所有条件都在同一张 attributes 行上判断,而实际数据是分散在多行的。
- 正确姿势是链式调用:
->whereHas('attributes', fn ($q) => $q->where('name', 'Color')->whereIn('value', ['Black'])),再接一个->whereHas('attributes', fn ($q) => $q->where('name', 'Sensitivity')->whereIn('value', ['1800 DPI'])) - 每个
whereHas对应一个独立EXISTS子查询,SQL 层面天然构成 AND 关系 - 动态构建时注意:
$values数组要校验非空,否则whereIn会报错或返回意外结果
真正容易被忽略的是:作用域封装的预加载逻辑,一旦暴露给外部调用者,就极可能被误拆成多次 with();而多层 whereHas 的嵌套深度和闭包写法,稍不注意就会漏掉某一层的过滤,导致前端渲染出断裂的层级。这些都不是语法错误,而是逻辑断点,调试时往往要翻好几层查询日志才能定位。











