Skip to main content
Category:

How to count query results of entityQuery in drupal 8 & 9

 

To obtain a count query from an existing query, use the countQuery() method.

$count_query = $query->countQuery();

 

$count_query is now a new Dynamic Select query with no ordering restrictions that when executed will return a result set with only one value, the number of records that would be matched by the original query. Because PHP supports chaining methods on returned objects, the following idiom is a common approach:

$num_rows = $query->countQuery()->execute()->fetchField();

 

For an entity query (implementing QueryInterface), the code is slightly different:

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

 

Example How to count query results of entityQuery in drupal 8 & 9

 $query = \Drupal::entityQuery('node')

                  ->condition('type', 'page')

                   ->condition('user_id', $user_id);

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

Riadh Rahmi

Senior Web Developer PHP/Drupal & Laravel

I am a senior web developer, I have experience in planning and developing large scale dynamic web solutions especially in Drupal & Laravel.

Web Posts

Search

Page Facebook