在 Laravel 9 中,嵌套预加载时,同时为预加载添加约束
1、现有的实现如下,是一个嵌套预加载,SQL 如下2、现在需要为 items 添加约束,最终实现如下3、生成的 SQL 如下,符合预期。如图1
return $builder->distinct()->with('items.orderItem')->get();
<pre class="wp-block-syntaxhighlighter-code">
// return $builder->distinct()->with('items.orderItem')->get();
return $builder->distinct()->with(['items' => function ($query) {
$query->whereRaw('(signed_quantity + signed_damaged_quantity) < return_quantity');
}, 'items.orderItem'])
->get();
</pre>
<pre class="wp-block-syntaxhighlighter-code">
select
*
from
`items`
where
`items`.`return_order_id` in (230)
and (signed_quantity + signed_damaged_quantity) < return_quantity
and `items`.`deleted_at_gmt` is null
</pre>
