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

Laravel如何合并查询条件优先返回指定类型的匹配数据

完全可以合并为单个查询,以下是两种常用实现方案:

方案1:纯单SQL查询(仅发起1次数据库请求)

逻辑完全在数据库层面执行,性能最优,对应的Laravel查询写法如下:

$data = Sale::where('customer', 'LIKE', '%peter%')
    ->where(function ($query) {
        $query->where('type', 'retailer')
            ->orWhere(function ($subQuery) {
                $subQuery->whereNotExists(function ($existQuery) {
                    $existQuery->from('sales')
                        ->where('type', 'retailer')
                        ->where('customer', 'LIKE', '%peter%');
                })->where('type', 'supplier');
            });
    })
    ->get();

核心逻辑:只要存在retailer类型的匹配数据,就只返回retailer的结果;不存在的情况下才返回supplier的匹配数据。

方案2:轻量EXISTS判断写法(可读性更高)

如果可以接受多1次极低开销的EXISTS查询,可以用更易懂的写法:

$hasRetailer = Sale::where('type', 'retailer')
    ->where('customer', 'LIKE', '%peter%')
    ->exists();

$data = Sale::where('customer', 'LIKE', '%peter%')
    ->where('type', $hasRetailer ? 'retailer' : 'supplier')
    ->get();

两种方案都完全符合业务需求,相比原来的写法,避免了先获取全量retailer数据再判断长度的冗余开销。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.09 23:09:00