1

This is the official Drupal::entityQuery function definition I found

public static function entityQuery($entity_type, $conjunction = 'AND') {
  return static::getContainer()
    ->get('entity.query')
    ->get($entity_type, $conjunction);
}

I also see that conditions can be added after the original query has been assigned to a variable

// original query
$query = \Drupal::entityQuery('node')
              ->condition('status', 1)
              ->sort('field_some_field', 'some_value');

// expand query with another condition
if (!empty($taxonomy_type)) {
  $query->condition('field_taxonomy_type', $taxonomy_type, 'IN');
}
  • Is this the correct way to query for nodes that contain a particular taxonomy type field?
  • How do I filter for nodes that contain a specific taxonomy term?
| improve this question | | | | |
2
  • Is this the correct way to query for nodes that contain a particular taxonomy type field?

\Drupal::entityQuery() is the correct approach, yes.

  • How do I filter for nodes that contain a specific taxonomy term?

Would you like to filter by the taxonomy term name? If so you need to get the taxonomy term ID and use that in your condition:

// Get an array of terms that have the name "foo".
$terms = \Drupal::entityTypeManager()
  ->getStorage('taxonomy_term')
  ->loadByProperties(['name' => 'foo']);

// Get the first term from the array.
$term = reset($terms);

// Get an array of nodes that reference the taxonomy term "foo"s ID.
$nodes = \Drupal::entityQuery('node')
  ->condition('status', 1)
  ->condition('field_my_taxonomy_term', $term->id(), '=')
  ->execute();

All Drupal entity references are done via the entities ID, so you will always be using that as your condition.

Also, entityTypeManager() & entityQuery() are basically the same thing, just structured slightly differently, so you can use whichever one you find most convenient.

| improve this answer | | | | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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