You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Laravel框架下如何为关联模型数据添加Where查询筛选条件

Laravel关联查询过滤关联结果解决方案

问题核心原因

whereHas(包括其语法糖whereRelation)仅负责筛选存在符合条件关联数据的主表记录,不会对关联查询的返回结果做过滤,你需要在with加载关联时同步附加条件,才能限制返回的关联明细内容。


解决方案

场景1:仅返回存在赠品明细的订单,且订单下仅保留赠品明细

你需要同时在with和whereHas中附加相同的过滤条件:

$bonus_item = SalesOrder::with(['product_sales' => function($query) {
    // 过滤关联返回的明细,仅保留赠品
    $query->where('bonus_item', true);
}])
->whereHas('product_sales', function($query) {
    // 过滤主表,仅保留存在赠品明细的销售订单
    $query->where('bonus_item', true);
})
->get();

如果你使用的是Laravel 9及以上版本,可以直接用内置的withWhereHas方法简化写法,效果完全一致:

$bonus_item = SalesOrder::withWhereHas('product_sales', function($query) {
    $query->where('bonus_item', true);
})
->get();

场景2:返回所有销售订单,仅将订单下的明细过滤为赠品(无赠品的订单对应明细为空数组)

直接去掉whereHas部分即可:

$bonus_item = SalesOrder::with(['product_sales' => function($query) {
    $query->where('bonus_item', true);
}])
->get();

内容的提问来源于stack exchange,提问作者Yoga Arliza

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.26 14:06:03