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

Laravel如何排除providers_total值为0的查询结果行?

问题描述

我正在执行查询并将结果保存到文件,查询语句如下:

$providers = groups::select('groups.id', DB::raw('count(DISTINCT groups_selection_filter.objectFK) as providers_total'))

但结果中存在providers_total计数为0的客户实例,例如:

1759 => array:5 [
    "id" => 1759
    "name" => "Test Client"
    "provider_count" => 0 
    "sport_count" => 1
    "sport_name" => "Soccer"
  ]

我需要移除这类客户结果,尝试过whereNot和HAVING方法:

->havingRaw(DB::raw('count(DISTINCT groups_selection_filter.objectFK)', '!==', 0))

但至今未成功,求可行解决思路?

可行解决思路
  • 修正havingRaw的写法:你当前的havingRaw嵌套错误,而且SQL里不等于用<>而非PHP的!==。正确写法二选一:
    // 写法1:用havingRaw
    ->havingRaw('count(DISTINCT groups_selection_filter.objectFK) <> 0')
    // 写法2:用Laravel的having方法
    ->having(DB::raw('count(DISTINCT groups_selection_filter.objectFK)'), '>', 0)
    
  • 更换关联类型:如果查询用了leftJoin,左联会保留所有groups记录(哪怕无匹配筛选数据)。改成join(内联),只保留有对应筛选记录的groups,自然不会出现计数为0的情况:
    $providers = groups::select('groups.id', DB::raw('count(DISTINCT groups_selection_filter.objectFK) as providers_total'))
        ->join('groups_selection_filter', 'groups.id', '=', 'groups_selection_filter.group_id') // 替换为你的实际关联字段
        ->groupBy('groups.id')
        ->get();
    
  • 左联下过滤空值:如果必须用左联,可通过whereNotNull筛选出有有效objectFK的记录,再分组统计:
    $providers = groups::select('groups.id', DB::raw('count(DISTINCT groups_selection_filter.objectFK) as providers_total'))
        ->leftJoin('groups_selection_filter', 'groups.id', '=', 'groups_selection_filter.group_id')
        ->whereNotNull('groups_selection_filter.objectFK')
        ->groupBy('groups.id')
        ->get();
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 08:00:56