Drupal 8 entity query across (through?) an entity reference field

Drupal Career Online begins March 1!

The next semester of our 12-week, 2x/week, best-practice-focused Drupal Career Online begins on March 1, 2021! Learn more!

If you write custom Drupal 8 (or 9) modules, then you've probably used the entity QueryInterface - which is accessible from the Drupal::entityQuery() static method. If not, then you're missing out on this incredibly useful tool that allows you to easily query a Drupal site for entities of any kind. 

For example, if you are looking for all nodes of type Movie that have a Release year of 2009, you can do something like this:

$result = \Drupal::entityQuery('node')
  ->condition('type', 'movie')
  ->condition('field_release_year', '2009')

But what if you want to base the condition on a value of a referenced entity? Maybe you want to find all nodes of type Movie where the director of the movie was born in 1981? Assume nodes of type Movie have an entity reference field to nodes of type Director, where one of the fields on the Director content type was Birth year. It's almost as easy to write an entityQuery condition for this situation as well:

$result = \Drupal::entityQuery('node')
 ->condition('type', 'movie')
 ->condition('field_director.entity:node.field_birth_year', '1981')

Note the entity:node bit in the second condition - this is what allows you to access fields in the referenced entity.


Brilliant tip, thanks very much. I'll definitely use this!

Submitted by david.qdoscc (not verified) on Thu, 07/09/2020 - 06:34

Sign up to receive email notifications of whenever we publish a new blog post or quicktip!