8

Using the EntityQuery API I am trying to add a group by clause to the query, however, it doesn't seem that one exists. The EntityQuery API does not have a groupBy() method.

Current Code:

$nodes = Drupal::entityQuery('node')
    ->condition('type', 'thing')
    ->condition('field_num_1', 'value', '=')
    ->condition('field_num_2', 'value', '=')
    ->range(0, 10)
    ->sort('title', 'ASC')
    ->execute();

Ideal Code:

$nodes = Drupal::entityQuery('node')
    ->condition('type', 'thing')
    ->condition('field_num_1', 'value', '=')
    ->condition('field_num_2', 'value', '=')
    ->groupBy('field_num_3')
    ->range(0, 10)
    ->sort('title', 'ASC')
    ->execute();
0

1 Answer 1

12

For aggregate queries, you need to use the separate method, from https://www.drupal.org/node/1918702:

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

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

groupBY() alone doesn't do anything. The normal entity query returns entity ID's. Always. It makes no sense to group by a field or anything else. Only in combination with aggregate.

7
  • Actually...I take that back, I think its working. Awesome! Thank you!
    – kknoer
    Commented Dec 18, 2015 at 20:53
  • Is it possible to sort the aggregate results by a field within an entity of one of the results. So example: Drupal::entityQueryAggregate('node')->groupBy('field_custom_name')->aggregate('nid', 'COUNT')->sortAggregate('field_custom_another_name', 'SUM', 'DESC')->execute();
    – kknoer
    Commented Jan 6, 2016 at 21:13
  • The statement "groupBy() alone doesn't do anything" is incorrect, it returns the values of the grouped column. However, most of the time this is not the result you want so you need to use the aggregate function as well. Commented Apr 1, 2016 at 9:15
  • Any way to return the nid list grouping by nid with a order? I mean, something like: ` $entityIds = \Drupal::entityQueryAggregate('transaction') ->condition('order_date', $from->getTimestamp(), '>') ->groupBy('nid') ->get the highest node ordering by order_date ->execute(); ` I don't want to count or something, only I want to get all transactions nid with a condition and, if any nid are in two rows, get the highest (or really, whatever!). Commented Sep 5, 2017 at 10:34
  • 1
    but how do you get the node ids contained on that one? i can see nid_count 2 but how do i know? Commented Sep 4, 2020 at 19:32

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.