Laravel Query Builder 按用户选择的sales_channel实现条件过滤
正确查询逻辑实现
核心思路是先把用户选中的销售渠道拆分为「Non-Amazon」和「其他渠道」两组,再用分组条件拼接规则,避免逻辑冲突。
完整代码示例
$request = $request->data; $orders = Orders::query(); if (!empty($request['sales_channel'])) { // 把传入的渠道数组转为集合方便拆分 $channelCollection = collect($request['sales_channel']); $includeNonAmazon = $channelCollection->contains('Non-Amazon'); $otherSelectedChannels = $channelCollection ->reject(fn($channel) => $channel === 'Non-Amazon') ->toArray(); // 用分组where封装条件,避免和全局其他查询条件冲突 $orders->where(function ($query) use ($includeNonAmazon, $otherSelectedChannels) { // 选中Non-Amazon时,无条件加对应渠道筛选 if ($includeNonAmazon) { $query->where('sales_channel', 'Non-Amazon'); } // 有其他选中渠道时,加「渠道匹配+total>0」的组合条件 if (!empty($otherSelectedChannels)) { $conditionClosure = function ($subQuery) use ($otherSelectedChannels) { $subQuery->whereIn('sales_channel', $otherSelectedChannels) ->where('total', '>', 0); }; // 已经加了Non-Amazon条件就用or,否则直接加条件 $includeNonAmazon ? $query->orWhere($conditionClosure) : $query->where($conditionClosure); } }); } $orders = $orders->get();
兼容低版本PHP写法
如果你的环境不支持PHP 7.4+的箭头函数,替换拆分渠道的代码即可:
$otherSelectedChannels = $channelCollection ->reject(function ($channel) { return $channel === 'Non-Amazon'; }) ->toArray();
逻辑验证
你给出的示例场景下,$request['sales_channel'] = ['Non-Amazon', 'Amazon.com'],最终生成的SQL条件等价于:
WHERE ( sales_channel = 'Non-Amazon' OR (sales_channel IN ('Amazon.com') AND total > 0) )
完全匹配预期返回结果,会返回所有Non-Amazon记录,加上Amazon.com渠道下total>0的记录,未选中的其他渠道会被直接过滤。
内容的提问来源于stack exchange,提问作者AJK
相关产品推荐
相关产品推荐

