Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Group By Eloquent ORM

I was searching for making a GROUP BY name Eloquent ORM docs but I haven't find anything, neither on google.

Does anyone know if it's possible ? or should I use query builder ?

like image 924
Hugo Gresse Avatar asked Mar 21 '14 14:03

Hugo Gresse


People also ask

How do you do groupBy in Laravel?

groupBy() will help you to getting data with group and you can count number records on that group. So, let's see bellow examples that will help you how to use groupBy() and groupBy() eloquent query in laravel. * Display a listing of the resource. * Display a listing of the resource.

Is eloquent an ORM?

Eloquent is an object relational mapper (ORM) that is included by default within the Laravel framework. An ORM is software that facilitates handling database records by representing data as objects, working as a layer of abstraction on top of the database engine used to store an application's data.

Where IS NOT NULL in Laravel?

Check if not null: whereNotNullSELECT * FROM users WHERE last_name IS NOT NULL; The equivalent to the IS NOT NULL condition in Laravel Eloquent is the whereNotNull method, which allows you to verify if a specific column's value is not NULL .

What is query Builder in Laravel?

Introduction. Laravel's database query builder provides a convenient, fluent interface to creating and running database queries. It can be used to perform most database operations in your application and works perfectly with all of Laravel's supported database systems.


2 Answers

Eloquent uses the query builder internally, so you can do:

$users = User::orderBy('name', 'desc')                 ->groupBy('count')                 ->having('count', '>', 100)                 ->get(); 
like image 61
Antonio Carlos Ribeiro Avatar answered Oct 27 '22 19:10

Antonio Carlos Ribeiro


Laravel 5

WARNING: As @Usama stated in comments section, this groups by AFTER fetching data from the database. The grouping is not done by the database server.
I wouldn't recommend this solution for large data set.

This is working for me (i use laravel 5.6).

$collection = MyModel::all()->groupBy('column'); 

If you want to convert the collection to plain php array, you can use toArray()

$array = MyModel::all()->groupBy('column')->toArray(); 
like image 39
chebaby Avatar answered Oct 27 '22 17:10

chebaby