Jonjie
2 months ago
434
8
Laravel

My groupBy is not grouping the data with 2 columns

Posted 2 months ago by Jonjie

I'm trying to get some answers from other devs but in my situation, it's a bit weird that this is not working. I just want to group the record using 2 columns (transaction_id and store_id). Please see my code below:

$transactions = DB::table('orders')
		->join('store', 'order.store_id', 'store.id')
            	->whereDate('order_date', '>=', $from)
            	->whereDate('order_date', '<=', $to)
            	->select(
                [
                	'store_id',
                	'transaction_id',
                	'currency',
                	'store_name',
			DB::raw('SUM(grand_total) as total'),
			DB::raw(COUNT(DISTINCT(`transaction_id`)) as orders_count)
                ]
            )
            ->groupBy('transaction_id')
            ->groupBy('store_id')
            ->get();

		return json_encode($transactions);

That code returns this:

0	Object { store_id: 32, transaction_id: "COD1000145148", … }
1	Object { store_id: 32, transaction_id: "COD1000145149", … }
2	Object { store_id: 34, transaction_id: "COD1000145151", … }
3	Object { store_id: 33, transaction_id: "COD1000145150", … }
4	Object { store_id: 34, transaction_id: "COD1000145152", … }
5	Object { store_id: 35, transaction_id: "COD1000145153", … }

So, these data only grouping by transaction_id and not the store_id. Any idea?

P.S. I also tried groupBy('transaction_id', 'store_id'). Also, I tried it to make an array but it still returns the same data.

Laravel version: 7

Please sign in or create an account to participate in this conversation.