1

查询以获取每月订单(每月总订单(计数)或每月总销售额(总和)):尝试了此查询,但它不起作用。还尝试了 StackOverflow 的其他结果,但我不明白它是如何使用 MongoDB 查询完成的。这是该问题的链接:select-sum-column-and-group-by-with-mongodb-and-laravel

$monthly_orders = Order::select(
    DB::raw('sum(total_amount) as sum'),
    DB::raw('YEAR(created_at) year, MONTH(created_at) month'),
)
->groupBy('month')
->get();

当我尝试通过按客户 ID 使用 group 来获取总金额时,它返回 sum 作为 null

$monthly_orders = Order::selectRaw('sum(total_amount) as sum, customer_id')
    ->groupBy('customer_id')
    ->pluck('sum', 'customer_id');

结果 :

Illuminate\Support\Collection {#2123 ▼
  #items: array:4 [▼
    "6098e5ff5977a25ee96a2a42" => null
    "60dbf87f7d8ffb7cdb2233d2" => null
    "605af409195d8e59e34893f2" => null
    "60ddae4a66fb69678e45f056" => null
  ]
}
4

1 回答 1

1

尝试使用rawaggregate

$monthly_orders = Order::raw(function ($collection) {
        return $collection->aggregate([
            [
                '$group' => [
                    "_id" => '$customer_id',
                    'customer_id' => ['$first' => '$customer_id'],
                    'sum' => ['$sum' => '$total_amount']
                ]
            ],

        ]);
    });

你可以用采摘

$monthly_orders->pluck('sum','customer_id')

按月分组

 $monthly_orders = Order::raw(function ($collection) {
            return $collection->aggregate([
                [
                    '$group' => [
                       "_id" => ['$month'=>'$created_at'],
                        'customer_id' => ['$first' => '$customer_id'],
                        'sum' => ['$sum' => '$total_amount']
                    ]
                ],
    
            ]);
        });
于 2021-07-18T09:55:03.213 回答