在 Laravel 9 中,嵌套预加载时,同时为预加载添加约束
1、现有的实现如下,是一个嵌套预加载,SQL 如下
1 | return $builder ->distinct()->with( 'items.orderItem' )->get(); |
2、现在需要为 items 添加约束,最终实现如下
1 2 3 4 5 | // 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(); |
3、生成的 SQL 如下,符合预期。如图1
1 2 3 4 5 6 7 8 | 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 |
近期评论