本文详细讲解如何在 Laravel 中构建以用户维度的订单与发货数量统计报表,支持自定义起止日期筛选。通过 withCount 与条件关联查询,精准获取每位用户在指定时间范围内的订单数和发货数。
不只是你,很多开发者在实现后台报表时,都会遇到一个典型需求:统计每个用户在特定时间段内的订单提交量和发货请求量。这篇文章将深入拆解如何利用你已定义的 Eloquent 关联关系(User ↔ Order、User ↔ Shipping),编写一个健壮、高效且易于维护的查询方案。
✅ 正确做法:统一时间条件 + 条件聚合
先从问题入手。你原始代码中可能存在几个常见误区:
- whereHas() 内部误调用 get(),直接破坏了链式查询;
- orWhereHas() 未包裹在闭包中,导致 SQL 逻辑混乱——OR 优先级干扰了主 WHERE;
- groupBy('created_at') 在子查询中毫无意义,反而阻碍计数聚合;
- orderByRaw('orders_count + shippings_count DESC') 虽然依赖 withCount 生成的字段,但原始查询并未确保所有用户都满足时间条件,可能导致部分计数为 0 的用户被排除。
因此,推荐的无 scope 版写法如下:
$report = User::withCount([ 'orders' => function ($q) use ($from, $to) { if (!empty($from)) { $q->whereDate('created_at', '>=', $from); } if (!empty($to)) { $q->whereDate('created_at', '<=', $to); } }, 'shippings' => function ($q) use ($from, $to) { if (!empty($from)) { $q->whereDate('created_at', '>=', $from); } if (!empty($to)) { $q->whereDate('created_at', '<=', $to); } }])->whereHas('shippings', function ($q) use ($from, $to) { if (!empty($from)) { $q->whereDate('created_at', '>=', $from); } if (!empty($to)) { $q->whereDate('created_at', '<=', $to); }})->orWhereHas('orders', function ($q) use ($from, $to) { if (!empty($from)) { $q->whereDate('created_at', '>=', $from); } if (!empty($to)) { $q->whereDate('created_at', '<=', $to); }})->orderByRaw('orders_count + shippings_count DESC')->paginate(25);
⚠️ 注意:whereHas(...)->orWhereHas(...) 的组合默认会生成 (has_shippings AND has_orders) OR ... 的歧义逻辑。为确保语义清晰——即筛选出「在该时间段内至少有一条订单 或 一条发货记录的用户」——建议在外层包裹 where(function () { ... }):
$report = User::withCount([ 'orders' => fn($q) => $this->applyDateFilter($q, $from, $to), 'shippings' => fn($q) => $this->applyDateFilter($q, $from, $to),])->where(function ($q) use ($from, $to) { $q->whereHas('shippings', fn($sub) => $this->applyDateFilter($sub, $from, $to)) ->orWhereHas('orders', fn($sub) => $this->applyDateFilter($sub, $from, $to));})->orderByRaw('orders_count + shippings_count DESC')->paginate(25);
同时在 Controller 或 Trait 中定义可复用的过滤方法:
protected function applyDateFilter($query, $from, $to){ if ($from) $query->whereDate('created_at', '>=', $from); if ($to) $query->whereDate('created_at', '<=', $to); return $query;}
✅ 进阶优化:添加局部作用域(推荐)
如果你想进一步提升代码的可读性和复用性,可以在 Order 和 Shipping 模型中添加局部作用域:
// AppModelsOrder.phppublic function scopeWhereDateBetween($builder, $from = null, $to = null){ if ($from) { $builder->whereDate('created_at', '>=', $from); } if ($to) { $builder->whereDate('created_at', '<=', $to); } return $builder;}
同样在 Shipping 模型中添加相同作用域。之后查询代码可以大幅简化为:
$report = User::withCount([ 'orders' => fn($q) => $q->whereDateBetween($from, $to), 'shippings' => fn($q) => $q->whereDateBetween($from, $to),])->where(function ($q) use ($from, $to) { $q->whereHas('shippings', fn($sub) => $sub->whereDateBetween($from, $to)) ->orWhereHas('orders', fn($sub) => $sub->whereDateBetween($from, $to));})->orderByDesc(DB::raw('orders_count + shippings_count'))->paginate(25);
? 使用说明与注意事项
- 日期格式:确保 $from 和 $to 为 Y-m-d 格式字符串(如 '2024-01-01'),whereDate() 会自动忽略时间部分,避免时区偏差;
- 空值处理:如果只输入开始日期或结束日期,上述逻辑依然能正确生效;
- 性能建议:为 created_at 字段添加数据库索引,尤其在大数据量场景下,效果非常显著;
- 前端校验:建议在表单侧限制 $to >= $from,并传递符合 ISO 标准的日期;
- 空结果处理:分页结果中,orders_count 和 shippings_count 均为整数(包含 0),无需额外判空。
最后,在 Blade 模板中直接使用即可:
@foreach($report as $user)@endforeach {{ $user->name }} {{ $user->orders_count }} {{ $user->shippings_count }} {{ $user->orders_count + $user->shippings_count }}
该方案兼顾了准确性、可维护性与扩展性,是 Laravel 报表类查询中较为成熟的实践之一。
