Entity Query — The query object that can query the any given entity type

Rahul Kumar
2 min readJun 2, 2021

In Drupal 8 for querying entities, there is no more EntityFieldQuery like Drupal 7, but there’s an entityQuery.
The entityQuery() is a static method on the \Drupal namespace, is a shortcut for doing so using the entity.query service.

entityQuery

The most important method in the EntityQuery class is the condition() method.

$bundle = ‘article’;
$query = \Drupal::entityQuery(‘node’);
$query->condition(‘type’, $bundle);
$query->condition(‘status’, PUBLISHED);
$query->range(0, 10);
$entity_ids = $query->execute();

Conditions allow us to limit our query in specific ways. It’s having following parameters :-

function condition($field, $value = NULL, $operator = NULL, $langcode = NULL)

Using functions like conditions, range gives us liberty to filter and limit the outcome of the query as per the requirements.

Two other methods that come in handy when building up the conditions of a query, orConditionGroup() and andConditionGroup(). It’s very well documented in the QueryInterface.

orConditionGroup
andConditionGroup

There are few other helper functions available for the better utilisation of the entityQuery.

public function exists($field, $langcode = NULL);

public function notExists($field, $langcode = NULL);

public function pager($limit = 10, $element = NULL);

public function range($start = NULL, $length = NULL);

public function sort($field, $direction = ‘ASC’, $langcode = NULL);

public function count();

public function tableSort(&$headers);

public function accessCheck($access_check = TRUE);

Any query run through entityQuery() is storage agnostic, so if you’re writing a contributed module or working on a site where it might be necessary to move to alternative entity storage in the future, all your queries will transparently use the new storage backend without any refactoring.

Keep Learning… Keep Sharing…
🙏

--

--

Rahul Kumar

Programmer | Freelancer | Thinker | Open Source | Tech Mantra