1

Query to get monthly orders (total orders per month(count) or total sales per month(sum)): Tried this query, but it is not working. Also tried with other results from StackOverflow, but I didn't understand how it is done with MongoDB query. This is the link to that question : 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();

When I try to get total amount by using group by customer ID , it is returning sum as null

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

Result :

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

1 Answers1

2

Try using raw and aggregate

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

        ]);
    });

you can use pluck

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

Group by month

 $monthly_orders = Order::raw(function ($collection) {
            return $collection->aggregate([
                [
                    '$group' => [
                       "_id" => ['$month'=>'$created_at'],
                        'customer_id' => ['$first' => '$customer_id'],
                        'sum' => ['$sum' => '$total_amount']
                    ]
                ],
    
            ]);
        });
John Lobo
  • 14,355
  • 2
  • 10
  • 20
  • Thanks , this is returning the sum based on customer IDs now, Thanks a lot. It would have been of great help if can help me to group by month using created at time stamp – RoshJ Jul 18 '21 at 11:12
  • 1
    @RoshJ try this "_id" => ['$month'=>'$created_at'], – John Lobo Jul 18 '21 at 11:16
  • Can u add it to the answer so that i can accept the answer – RoshJ Jul 18 '21 at 11:19