Find Entity using Drupal EntityQuery

Submitted by editor on Sun, 05/29/2016 - 11:38

How to Find Entity (nodes, taxonomy terms, users ...) using Drupal EntityQuery ?

You can find any entity using Drupal 8 EntityQuery System.

Example 1. Taxonomy

Get list of all taxonomy terms
    $query = \Drupal::entityQuery('taxonomy_term');
    $tids = $query->execute();

Get term id of the vocabulary 'tags'
    $query = \Drupal::entityQuery('taxonomy_term');
    $query->condition('vid', 'tags');
    $tids = $query->execute();

Example 2. Node

Find all nodes where the title contains 'drupal'
    $query = \Drupal::entityQuery('node');
    $query->condition('title', '%drupal%','LIKE');
    $nids = $query->execute();

Example 3. User

Fiend all users who's name contains 'admin'
    $query = \Drupal::entityQuery('user');
    $query->condition('name', '%admin%','LIKE');
    $ids = $query->execute();

Example 4. Node with OR condition

    $query = \Drupal::entityQuery('node');
    $group = $query->orConditionGroup()
        ->condition('type', 'page')
        ->condition('type', 'article');
    $entity_ids = $query
        ->condition('title', '%drupal%','LIKE')

Example 5. With multiple AND + OR conditions

$query->condition('type', $type);
$query_or = $query->orConditionGroup();

$query_and = $query->andConditionGroup()
  ->condition('end1', $end1)
  ->condition('end2', $end2);

$query_and = $query->andConditionGroup()
  ->condition('end1', $end2)
  ->condition('end2', $end1);


Example 6. Check A field value is NULL or is Not Null

$query = \Drupal::entityQuery('the_entity');
$query->notExists('field_to_check');//Check A field value is NULL
$query->exists('field_to_check');//Check A field value is NOT NULL
ids = $query->execute();


Adrien Lasserre (not verified)

Wed, 06/08/2016 - 15:43

For a role named 'reviewer' :

 $uids = \Drupal::entityQuery('user')->condition('roles.target_id','reviewer')->execute();



Add new comment

This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.
Enter the characters shown in the image.