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

Laravel 10中如何按barcode和location汇总对象数组的quantity?

解决方案

你的问题出在仅按barcode单字段分组,没有将location作为分组的一部分,导致不同位置的同条码条目被错误合并。要实现「相同条码+相同位置才汇总数量」的需求,需要同时按barcode和location两个字段分组。

修正后的代码

$collection
    ->groupBy(['barcode', 'location']) // 按条码和位置共同分组
    ->map(function ($group) {
        // 取分组内第一个条目的基础字段,汇总数量
        $firstItem = $group->first();
        return [
            'id' => $firstItem['id'],
            'barcode' => $firstItem['barcode'],
            'description' => $firstItem['description'],
            'quantity' => (string)$group->sum(function ($item) {
                return (int)$item['quantity']; // 先转整数再求和,避免字符串拼接
            }),
            'location' => $firstItem['location'],
        ];
    })
    ->values(); // 重置数组索引

关键修正点

  1. 多字段分组:groupBy(['barcode', 'location'])会把barcode和location完全相同的条目归为一组,满足「不同位置分开统计」的要求。
  2. 字段名修正:原代码里用了qty,但你的数据字段是quantity,要统一字段名。
  3. 类型处理:因为quantity是字符串类型,求和时先转整数避免字符串拼接(比如"3"+"1"会变成"31"),最后再转回字符串匹配你的期望格式。

验证结果

用你的示例数据运行上述代码,会得到和你期望完全一致的结果:

[
  {
    "id": 1,
    "barcode": "555",
    "description": "pencil",
    "quantity": "4",
    "location": "drawer1"
  },
  {
    "id": 3,
    "barcode": "123",
    "description": "paper",
    "quantity": "9",
    "location": "drawer2"
  },
  {
    "id": 5,
    "barcode": "123",
    "description": "paper",
    "quantity": "8",
    "location": "drawer1"
  }
]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.22 13:17:15