Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Laravel – multiple select query

I want to pull data from two columns in my database table, I’m not very good at querying SQL. When I do this query I get this error:

Expression #2 of SELECT list is not in GROUP BY clause and contains…

What am I missing?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

My query:

$top_orders = OrderItem::select('name','productId', DB::raw('count(name) as total'))->groupBy('name')->orderBy('total','desc')->take(5)->get();

>Solution :

It is SQL Standard feature and its not anything to do with laravel. You can add required column to group by or use an aggragete function like sum etc.

If you specify the GROUP BY clause, columns referenced must be all the columns in the SELECT clause that do not contain an aggregate function. These columns can either be the column, an expression, or the ordinal number in the column list.

$top_orders = OrderItem::select('name','productId', DB::raw('count(name) as total'))
  ->groupBy('name','productId')
  ->orderBy('total','desc')
  ->take(5)
  ->get();
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading