Change record status: 
Project: 
Introduced in branch: 
8.x
Description: 

EntityFieldQuery in Drupal 7 did not support GROUP BY and the assorted aggregation functions like COUNT/MIN/MAX. Entity Query in Drupal 8 supports this construct.

Let's assume you want the amount of nodes per node type.

$query = Drupal::entityQueryAggregate('node');

$result = $query
  ->groupBy('type')
  ->aggregate('nid', 'COUNT')
  ->execute();

In contrast to a normal entity query the result does not have to contain entity IDs. In this example it would look like

array(
  0 => 
  array(
    'type' => 'article',
    'nid_count' => '1',
  ),
)

Additional functions you can call are conditionAggregate to filter by certain aggregation functions and sortAggregate to order by calculated values.

Impacts: 
Module developers

Comments

rudiedirkx’s picture

Why `nid_count`? Any docs on that?

mradcliffe’s picture

Also note that conditionAggregate is database driver specific code. You should use a HAVING query to do that.