The Drupal 8 version of EntityFieldQuery

By Daniel Sipos

How to Build a Drupal 8 Module

Even though Drupal 7 core fell short of a proper way of handling its brand new entity system (we currently rely on the great Entity module for that), it did give us EntityFieldQuery. For those of you who don’t know, EntityFieldQuery is a very powerful querying class used to search Drupal entities programatically (nodes, users, etc).

It provides a number of methods that make it easy to query entities based on conditions such as field values or class properties. If you don’t know how it works, feel free to check out this documentation page or this great tutorial on the subject.

In this article I am going to talk about what we have in Drupal 8 for querying entities. There is no more EntityFieldQuery, but there’s an entity.query service that will instantiate a query object for a given entity type (and that implements the \Drupal\Core\Entity\Query\QueryInterface). We can access this service statically through the \Drupal namespace or using dependency injection.

First up, we’ll look at querying node entities and then we’ll see how to load them. The same techniques will work with other content entities as well (users, comments etc), but also with configuration entities, and that’s really cool.

The entity query service

As mentioned, there are two ways we can access the entity.query service that we use for querying entities. Statically, we can do this:

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

Instead of node, we can specify any other entity type machine name and what we get inside the $query variable is the query object for our entity type. The entityQuery() static method on the \Drupal namespace is a shortcut for doing so using the entity.query service.

Alternatively (and the highly recommended approach) is to use dependency injection.

If you have access to the container, you can load the service from there and then get the right query object:

$entity_query_service = $container->get('entity.query');
$query = $entity_query_service->get('node');

As you can see, we use the get() method on the entity_query service to instantiate a query object for the entity type with the machine name passed as a parameter.

Querying entities

Let’s illustrate a couple of examples of querying for node entities using this object.

A very simple query that returns the published nodes:

$query = \Drupal::entityQuery('node')
    ->condition('status', 1);
$nids = $query->execute();

$nids will be an array of entity ids (in our case node ids) keyed by the revision ids (if there is revisioning enabled for the entity type) or the entity ids if not. Let’s see an example in which we add more property conditions as well as field conditions:

$query = \Drupal::entityQuery('node')
    ->condition('status', 1)
    ->condition('changed', REQUEST_TIME, '<')
    ->condition('title', 'cat', 'CONTAINS')
    ->condition('', 'cats');

$nids = $query->execute();

In this query, we retrieve the node ids of all the published nodes that have been last updated before the current time, that have the word cat inside their title and that have a taxonomy term called cats as a reference in the field_tags.

As you can see, there is no more distinction between propertyCondition and fieldCondition (as there is in D7 with EntityFieldQuery). Additionally, we can include conditions based on referenced entities tacking on the entity.(column) to the entity reference field name.

An important thing to note is that we also have the langcode parameter in the condition() method by which we can specify what translation of the node should be included in the query. For instance, we can retrieve node IDs that contain a specific value inside of a field in one language but another value inside the same field for another language.

For more information on the condition() method you should consult the API documentation.

The next thing we are going to look at is using condition groups (both AND and OR) for more powerful queries:

$query = \Drupal::entityQuery('node')
    ->condition('status', 1)
    ->condition('changed', REQUEST_TIME, '<');

$group = $query->orConditionGroup()
    ->condition('title', 'cat', 'CONTAINS')
    ->condition('', 'cats');

$nids = $query->condition($group)->execute();

Above, we altered our previous query so as to retrieve nodes that either have the cat string in their title or have a reference to the term called cats in their field_tags field. And we did so by creating an orConditionGroup object that we then pass to the query as a condition. And we can group together multiple conditions within a andConditionGroup as well.

There are many other methods on the QueryInterface that can extend the query (such as for sorting, range, etc). I encourage you to check them out in the documentation and experiment with them. For now, though, let’s take a quick look at what to do with the result set.

Loading entities

As I mentioned above, the execute() method on the query object we’ve been working with returns an array of entity IDs. Supposedly we now have to load those entity objects and work with them. How do we do that?

In Drupal 7 we had the entity_load() function to which we passed an array of IDs and that would return an array of objects. In Drupal 8, this helper function is maintained and you can use it pretty much in the same way, except only for one entity at a time:

$node = entity_load('node', $nids[1]);

And the return value is a node object. To load multiple nodes, you can use the entity_load_multiple() function:

$nodes = entity_load_multiple('node', $nids);

Which then returns an array of entity objects keyed by their ids.

A bonus nugget of information is that both of these functions are wrappers for the storage manager of the entities in question. They basically retrieve the storage manager statically and then call the load() and loadMultiple() methods, respectively, on it:

Statically, you could do similarly:

$node_storage = \Drupal::entityManager()->getStorage('node');

// Load multiple nodes
// Load a single node

But better yet, you could use dependency injection and retrieve the storage class from the container:

$node_storage = $container->get('entity.manager')->getStorage('node');

And then proceed with the loading. Using dependency injection is usually the recommended way to go when it’s possible, i.e. when working within a class. This makes it easier to test your class and better decouples it from the rest of the application.


In this article we’ve seen how to work with querying and loading entities in Drupal 8. There has been an overhaul of the D7 EntityFieldQuery class that turned into a robust API for querying both content and configuration entities. We’ve looked at querying content entities but the system works just the same with config entities. And that is a bit of a win for the new Drupal 8 entity system.

We’ve also seen how to load entities based on the IDs resulted in these queries and what is actually behind the wrapper functions that perform these operations. Next up, we are going to look at defining our own content entity type in Drupal 8. For a refresher on how we do it in Drupal 7, you can check out these Sitepoint articles on the subject.

Daniel Sipos
Meet the author
Daniel Sipos is a Drupal developer who lives in Brussels, Belgium. He works professionally with Drupal but likes to use other PHP frameworks and technologies as well. He runs, a Drupal blog where he writes articles and tutorials about Drupal development, theming and site building.
  • Wolf_22

    It will be interesting to see how this is used in conjunction to Views. I bet we’re on the verge of seeing some pretty wicked queries with all this, which is going to take Drupal to the next level of displaying information. Additionally, all of this will make creating templates ten-times easier.

    I’m curious about something… Is it always necessary to load entire objects if, say, you need only 1 piece of each node being used? I.e. – what if you only need a title? Lastly, is it necessary to unset() any of the objects created from, say, entity_load(), etc.?

    Thanks for the article, Daniel. Very good stuff! :)

    • Danny

      Hey there,

      Not likely. You will still have the DB abstraction layers you can use to make custom queries. So you can search for whatever you want :)


      • Wolf_22

        It’s debatable but I’d bet everything I have that a large number of Drupal users know very little about things like making their own themes, modules, modeling queries around aspects within database abstraction layers… And for a number of those that *do* it took a considerable amount of time to understand the necessary API concepts. If these changes bridge that gap of learning throughput via a culmination of better (i.e. – easier to understand) documentation, easier to implement Views modifications, more maintainable code not only in core but also with the many plugins, etc., then I’d think that it would have a major impact on how data is extracted because overall, it will equate to a more usable system (not just from standard run-of-the-mill users but also for developers who make interfaces easier to use at quicker paces).

      • Mike Carper

        I’ve extended the d7 efq object allowing for retrieval of field and property values. Also doing complex things by joining efq.

  • Bevan Rudge

    This makes me want to write raw SQL.

    • Si Hobbs

      Humour aside, this means you’d need to abstract your query for each entity type, and then abstract your query further for alternative backends such as mongo, and etc.

  • andre

    hi all,
    i have some problems with custom block content.
    So, i create block custom type and add custom block with it. Now , i see it generate block in block layout.
    My question, how i get content block with extra filed by code. Because drupal 8 does not support block_load function. Please help me to solve it. Thanks

    • Tal Shitrit

      entity_load(‘block_content’, …)

  • John Ennew

    Thanks for sharing!

  • Damian

    Thanks for an excellent set of tutorials.

  • mesch

    Thanks for this series, Daniel.

    Do you have any thoughts on where re-usable query methods should be placed in a module? That is, methods that can be readily called both by entity handlers (e.g. form classes) and controllers.

    Basically I’m looking for similar functionality to Symfony 2 w/ Doctrine, whereby you put all your query methods in the object repository and then can fetch that repository easily wherever you have access to the entity manager.

  • Deovrat Jalgaonkar

    Very good explanation.
    Thanks Daniel !!

  • Cristian Radu

    I need to set a condition with “NOT IN” on a relation. So far the only thing that works is:

    $q = Drupal::entityQuery(‘node’);
    $group = $q->orConditionGroup()
    ->condition(‘field_some_relation’, [1,2,3,4], ‘NOT IN’)
    ->condition(‘field_some_relation’, NULL, ‘IS NULL’);

    $ids = $q->execute();

    orConditionGroup() forces the join to left (normally is set to inner join) and the second condition (is null) includes the nodes that have no value to the relation fields (so no entry to the joined field table).
    As I said, this works but I hope there is a more elegant solution cause this looks like a hack to me.

    And another thing that bothers me is the fact that one can supply any string value for $operator and is passed along into the SQL query.

  • Cristian Radu

    I need to set a condition with “NOT IN” on a relation. So far the only thing that works is:

    $q = Drupal::entityQuery(‘node’);
    $group = $q->orConditionGroup()
    ->condition(‘field_some_relation’, [1,2,3,4], ‘NOT IN’)
    ->condition(‘field_some_relation’, NULL, ‘IS NULL’);

    $ids = $q->execute();

    orConditionGroup() forces the join to left (normally is set to inner join) and the second condition (is null) includes the nodes that have no value to the relation fields (so no entry to the joined field table).
    As I said, this works but I hope there is a more elegant solution cause this looks like a hack to me.

    And another thing that bothers me is the fact that one can supply any string value for $operator and is passed along into the SQL query.

  • Christophe Jossart

    Thanks Daniel ! A small update since the deprecation of entity.manager that should be replaced by entity_type.manager.

    So it becomes :
    – static : Drupal::entityTypeManager()->getStorage(‘node’)->load($nid);
    – dependency injection : $container->get(‘entity_type.manager’)->getStorage(‘node’)->load($nid);

  • Alla

    Hello Daniel,

    How can I count the number of references the Entity has?

    $storage = Drupal::entityManager()->getStorage(‘step’);
    $query = $storage->getQuery()->condition(‘id’, $entity->id());

    return $query->count(‘processes’)->execute();

  • Venkatesh Somu

    Would you please share the above example code completely for my practice example.It will be useful for all.
    Please share the module completely

Learn Coding Online
Learn Web Development

Start learning web development and design for free with SitePoint Premium!