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')
->condition($group)
->execute();
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_or->condition($query_and);
$query_and = $query->andConditionGroup()
->condition('end1', $end2)
->condition('end2', $end1);
$query_or->condition($query_and);
$query->condition($query_or);
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
//OR
$query->exists('field_to_check');//Check A field value is NOT NULL
ids = $query->execute();
Comments6
How to query user by role
For a role named 'reviewer' :
$uids = \Drupal::entityQuery('user')->condition('roles.target_id','reviewer')->execute();
Voilà a
Merci
Thank you
Term Reference
How Can I use term id in condition
field.tags.target_id should…
field.tags.target_id should do the trick
Edit previous comment :…
Edit previous comment : field_tags.target_id
Thank you!
This save my day!