Search code examples
phpmysqllaravelgroup-bylaravel-5.7

Select multiple column in groupBy laravel 5.7


I am using Laravel 5.7 and i need to generate top selling products of current month for my reports. So i join two table products and sells. I want three columns in return which are sell_quantity, product_name*, and product_id.

So i pass those three column inside selectRaw and the query is like below:

 $top_items = Sell::whereBetween('date', [Carbon::now()->startOfMonth(), Carbon::now()->endOfMonth()])->leftJoin('products', 'products.id', '=', 'sells.product_id')->selectRaw('sum(sells.quantity) as quantity, products.name, product_id')->groupBy('product_id')->limit(10)->orderBy('sells.quantity', 'desc')->get();

But when i execute i got an error which said products.name isn't in GROUP BY. My question is it required to pass all the parameter in select which i placed inside groupBy.


Solution

  • Try this

    $top_items = Sell::whereBetween('date', [Carbon::now()->startOfMonth(), Carbon::now()->endOfMonth()])
        ->leftJoin('products', 'products.id', '=', 'sells.product_id')
        ->selectRaw('sum(sells.quantity) as quantity, products.name, sells.product_id')
        ->groupBy('sells.product_id', 'products.name')
        ->limit(10)
        ->orderBy('quantity', 'desc')
        ->get();