2

My code:

$query = \Drupal::entityQuery('node');
$query->condition('status', 1);
$query->condition('type', 'news');
$query->pager(9);

$count = $query->count()->execute();

However my $count value is always 9 (because of the pager).

How can i get the total count of the query? (All results)

1
  • You need to perform a separate query for the count, or find a way to shoehorn this into it
    – Clive
    Nov 28, 2017 at 9:07

2 Answers 2

2

// Use clone.

$query = \Drupal::entityQuery('node');
$query->condition('status', 1);
$query->condition('type', 'news');
$query->pager(9);
**$count_query = clone $query;**

$items = $query->execute();

$count = $count_query->count()->execute()
1

You can't reuse the same query object for these two different things. ->pager() permanently turns the query into a paged query, and ->count() permanently turns it into a count query. Trying to do both results in unpredicted behavior depending on execution order.

The code you pasted actually does return the total count, because count trumps pager if both are set when the query is first executed. But afterwards it's a count query and will always return a number:

// With 50 nodes in the database:

$query = \Drupal::entityQuery('node');
$query->condition('status', 1);
$query->condition('type', 'news');
$query->pager(9);

$count = $query->count()->execute();
// $count is 50, the ->pager() is ignored.

$items = $query->execute();
// $items is 50, not an array. It's permanently a count query now.

Flipping the execution order:

$query = \Drupal::entityQuery('node');
$query->condition('status', 1);
$query->condition('type', 'news');
$query->pager(9);

$items = $query->execute();
// $items is an array with 9 nodes.  

$count = $query->count()->execute();
// $count is 9.

Instead, you need to use two separate queries here:

$count = \Drupal::entityQuery('node');
  ->condition('status', 1);
  ->condition('type', 'news');
  ->count()
  ->execute();

$items = \Drupal::entityQuery('node');
  ->condition('status', 1);
  ->condition('type', 'news');
  ->pager(9)
  ->execute();
3
  • i for now fixed it with "global $pager_total_items;"
    – Paul
    Nov 28, 2017 at 13:44
  • How does that fix it?
    – Kevin
    Nov 28, 2017 at 14:25
  • Hm, it's true; pager queries do still store their total counts in a global variable. I believe the numeric index in that array can be set in the second argument to pager(). Obviously terrible architecture in an OO context, but it does save an extra query. Nov 28, 2017 at 15:32

Your Answer

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

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