Can't figure out how to construct a query to obtain a sum of a field programmatically. The folowing code works fine for counts:

$count = Drupal::entityQuery('node')
  ->condition('type', 'artefacts')
  ->condition('status', '1')
  ->condition('default_langcode', 1)
  ->condition('field_city', $id)

but no matter how I try I can't figure out how to obtain the sum. There is a lot of examples for Drupal 7 but can't find a single one for Drupal 8.

$sum = Drupal::entityQuery('node')
  ->condition('type', 'cities')
  ->condition('status', '1')
  ->condition('default_langcode', 1)
  ->condition('field_country', $id)
  ->aggregate('sum(field_artefact_count)', 'total')

seems to return '1' in any circumstances. The documentation on Query class is terse to put it mildly. Apparently execute() is supposed to return an array of entity id's but what's the entity id of a single total of a table of a 1000 records?


Use QueryAggregateInterface::execute:

$result = \Drupal::entityQueryAggregate('node')
  ->aggregate('nid', 'sum')
  ->condition('status', NodeInterface::PUBLISHED)

The result returned is keyed by fieldname and aggregate function:

$sum = $result['0']['nid_sum'];
| improve this answer | |
  • Wow, thanks a ton! Now the only question remaining is how I could possibly find it unless I knew the exact class/interface name beforehand ;) No combination of Drupal 8 / query / aggregate / total / sum would bring it up on google... – Marassa Jul 16 '19 at 7:19

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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