Group By and Having

groupBy

Passing a single string will group by that one column.

QueryBuilder
query.from( "users" )
    .groupBy( "country" );
MySQL
SELECT *
FROM `users`
GROUP BY `country`

You can also pass a list of column names. A single comma (",") will be used as the delimiter.

QueryBuilder
query.from( "users" )
    .groupBy( "country,city" );
MySQL
SELECT *
FROM `users`
GROUP BY `country`, `city`

An array of column names can be provided.

QueryBuilder
query.from( "users" )
    .groupBy( [ "country", "city" ] );
MySQL
SELECT *
FROM `users`
GROUP BY `country`, `city`

Calling groupBy multiple times will to the current groups.

QueryBuilder
query.from( "users" )
    .groupBy( "country" )
    .groupBy( "city" );
MySQL
SELECT *
FROM `users`
GROUP BY `country`, `city`

An Expression can be passed in place of a column.

QueryBuilder
query.from( "users" )
    .groupBy( query.raw( "DATE(created_at)" ) );
MySQL
SELECT *
FROM `users`
GROUP BY DATE(created_at)

having

Adds a having clause to a query.

QueryBuilder
query.from( "users" )
    .groupBy( "email" )
    .having( "email", ">", 1 );
MySQL
SELECT *
FROM `users`
GROUP BY `email`
HAVING `email` > ?

Expressions can be used in place of the column or the value.

QueryBuilder
query.from( "users" )
    .groupBy( "email" )
    .having( query.raw( "COUNT(email)" ), ">", 1 );
MySQL
SELECT *
FROM `users`
GROUP BY `email`
HAVING COUNT(email) > ?

Last updated