代码之家  ›  专栏  ›  技术社区  ›  Marcus Christiansen

Laravel groupBy列并根据数量列添加总计

  •  0
  • Marcus Christiansen  · 技术社区  · 8 年前

    我使用以下列“ 订单id、产品id、数量 "

    DB::table('order_product')->selectRaw('*, count(*)')->groupBy('product_id');
    

    然而,有些产品在一个订单中出现多次。如何将每个乘积乘以 数量 列,然后按分组 产品id

    最后,我需要得到按产品分组的所有订单的总数。

    编辑

    enter image description here

    13

    1 回复  |  直到 8 年前
        1
  •  2
  •   Tim Biegeleisen    8 年前

    我认为您需要使用数量字段的总和对每个产品进行聚合。因此,以下各项应起作用:

    DB::table('order_product')->selectRaw('product_id, SUM(qty)')->groupBy('product_id');
    

    这将对应于以下原始MySQL查询:

    SELECT
        product_id,
        SUM(qty)
    FROM order_product
    GROUP BY
        product_id