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

Laravel查询编写问题:筛选符合用户关联家电、品牌ID的工单数据

Laravel 多条件筛选工单查询写法

最优方案:数据库层面筛选(推荐)

直接在SQL查询阶段完成条件过滤,无需查询全量工单到内存,性能远高于集合层面过滤:

$userAppliances = DB::table('user_appliances')
            ->where('user_id', 5)
            ->pluck('appliance_id')
            ->toArray();

$userBrands = DB::table('user_brands')
            ->where('user_id', 5)
            ->pluck('brand_id')
            ->toArray();

$ticketList = Ticket::with('appliance', 'brand')
            // 筛选设备ID在用户关联设备数组中
            ->whereIn('appliance_id', $userAppliances)
            // 筛选品牌ID在用户关联品牌数组中
            ->whereIn('brand_id', $userBrands)
            ->get();

dd($ticketList);

备用方案:集合层面过滤

如果确实需要先获取全量工单再做筛选,使用集合filter方法而非map,map用于修改集合元素返回值,filter才用于筛选符合条件的元素:

$ticketList = Ticket::with('appliance', 'brand')->get();

$userAppliances = DB::table('user_appliances')
            ->where('user_id', 5)
            ->pluck('appliance_id')
            ->toArray();

$userBrands = DB::table('user_brands')
            ->where('user_id', 5)
            ->pluck('brand_id')
            ->toArray();

$ticketList = $ticketList->filter(function ($ticket) use ($userAppliances, $userBrands) {
    return in_array($ticket->appliance_id, $userAppliances) && in_array($ticket->brand_id, $userBrands);
})->values(); // 可选:重置集合的键为连续索引

dd($ticketList);

原有代码问题说明

  • 先全量get工单再过滤,数据量大时内存占用高、性能差
  • 错用map方法做筛选,map不会过滤元素只会修改元素返回值
  • 在单个Ticket模型实例上调用where方法,该方法为查询构造器方法,单个模型实例无此方法
  • 匹配值是否在数组中不能用where等于判断,需要用whereIn(SQL层面)或in_array(PHP层面)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.23 17:15:07