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

如何在Laravel中获取上月订单项销售报表并合并同商品的销量与金额

方案1:查询层直接聚合(性能最优)

直接从商品维度查询,通过SQL聚合直接得到汇总结果,避免后续多余处理,代码如下:

控制器代码

use Carbon\Carbon;

// 直接查询上月所有已售商品的汇总数据
$items = Item::selectRaw('items.*, SUM(order_items.quantity) as total_quantity, SUM(order_items.price) as total_price')
    ->join('order_items', 'items.id', '=', 'order_items.item_id')
    ->join('orders', 'orders.id', '=', 'order_items.order_id')
    ->whereYear('orders.created_at', Carbon::now()->subMonth()->year)
    ->whereMonth('orders.created_at', Carbon::now()->subMonth()->month)
    ->groupBy('items.id')
    ->get();

Blade模板代码

<table>
  <tr>
    <th>Item Name</th>
    <th>Quantity</th>
    <th>Price</th>
  </tr>
  @foreach ($items as $item)
  <tr>
    <td>{{ $item->name }}</td>
    <td>{{ $item->total_quantity }}</td>
    <td>{{ $item->total_price }}</td>
  </tr>
  @endforeach
</table>

方案2:集合层处理(无需修改原有查询逻辑)

如果不想改动原有订单查询逻辑,可直接基于已查询到的订单集合做聚合处理:

控制器代码

在原有$orders查询后追加如下代码:

$itemStats = $orders->pluck('items')
    ->flatten()
    ->groupBy('id')
    ->map(function ($itemGroup) {
        return [
            'name' => $itemGroup->first()->name,
            'total_quantity' => $itemGroup->sum('pivot.quantity'),
            'total_price' => $itemGroup->sum('pivot.price')
        ];
    });

Blade模板代码

@foreach ($itemStats as $stat)
  <li>{{ $stat['name'] }}, {{ $stat['total_quantity'] }}, {{ $stat['total_price'] }}</li>
@endforeach

注意事项

原有查询仅用whereMonth过滤存在跨年问题,建议同时补充年份过滤条件,避免统计到往年同月的订单数据。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 12:36:03