Laravel查询优化:无对应记录时status_count显示0的实现
解决Laravel查询中展示所有ORD类型状态并补全0计数的问题
嘿,我明白你的需求了——要把所有type为ORD的状态都列出来,哪怕当前登录用户没有对应状态的订单,也要让status_count显示0对吧?
你现在的查询逻辑有个小问题:你是以OrderHeader作为主表左连status,再加上user_id的全局where条件,这相当于把左连接变成了内连接,自然拿不到那些用户没有订单的状态。我帮你调整一下查询逻辑,核心是换主表+正确处理空计数:
$orderStatistics = Status::select( 'status.id', 'status.name', 'status.description', 'status.type', 'status.code', DB::raw('status.code as order_status'), // 确保无订单时也能拿到对应状态的code DB::raw('count(order_header.id) as status_count') // 有订单统计数量,无则自动为0 ) ->leftJoin('order_header', function($join) { $join->on('status.code', '=', 'order_header.order_status') ->where('order_header.user_id', auth()->user()->id); // 用户筛选放在连表条件里,不影响左连结果 }) ->where('status.type', 'ORD') ->orderBy('status.id') ->groupBy('status.id', 'status.name', 'status.description', 'status.type', 'status.code') ->get();
几个关键的调整点:
- 主表切换为
Status:先把所有type=ORD的状态都查出来,再左连用户的订单记录,这样就能保证所有目标状态都出现在结果里 - 用户条件放在连表闭包中:如果把
user_id放在全局where里,会直接过滤掉没有对应订单的状态,放在连表条件里才是真正的左连接 - 计数逻辑优化:用
count(order_header.id)而不是count(*),因为左连后无匹配订单时order_header.id为null,count()会忽略null值,自动返回0,完美符合你的需求 order_status字段处理:直接用status.code赋值,避免无订单时该字段为null,和你期望的结果格式保持一致
这样调整后,就能得到你想要的结果——包括那条用户没有订单的TST状态,对应的status_count会显示0。
内容的提问来源于stack exchange,提问作者user13080158
相关产品推荐
相关产品推荐

