<?php
use Drupal\Core\Config\Entity\Query\Query;
use Drupal\Core\Entity\Query\QueryFactory;
use Drupal\Core\Entity\Query\QueryInterface;
// Condition operators (3rd param):
'=', '<>', '>', '>=', '<', '<=', 'STARTS_WITH', 'CONTAINS', 'ENDS_WITH', 'IN', 'NOT IN', 'BETWEEN'.
////////////////////////
////////////////////////
// IMPORTANT //
/////////////////////////
/////////////////////////
// To make entityQuery work correctly bypassing the node pemission access restriction
// YOU must add the folowing condintion:
->addMetaData('account', User::load(1))
$this->entityQuery = \Drupal::entityTypeManager()->getStorage('node')->getQuery();
// Returns an aggregated query object for a given entity type.
$query = $this->entityQuery->getAggregate('node', 'AND');
// For example I want to filter nodes whose NIDs are between 10 and 50.
// But I would also like to see which NID is the lowest and which is the highest.
$result = \Drupal::entityQueryAggregate('node')
->aggregate('nid', 'MIN', NULL, 'nid_min')
->aggregate('nid', 'MAX', NULL, 'nid_max')
->condition('nid', [10, 50], 'BETWEEN')
->execute();
// $result[0]['nid_min'] and $result[0]['nid_max']
// groupBY() alone doesn't do anything. Only in combination with aggregate.
$query = Drupal::entityQueryAggregate('node');
$result = $query
->groupBy('type')
->aggregate('nid', 'COUNT')
->execute();
// Conditions with related user entity example.
$node_ids = $this->entityQuery->get('node')
->condition('type', 'article')
->condition('status', 1)
->condition('uid.entity.name', '%admin%', 'LIKE')
->condition('uid.entity.status', 1)
->execute();
// Field example.
// If you need a simple check whether or not a particular field exists you can use the exists() or notExists() methods.
$query = \Drupal::entityQuery('commerce_product')
->condition('status', 1)
->condition('type', 'doc')
->notExists('field_tags')
->condition('field_doc_category', 134);
// Count example.
$query = \Drupal::entityQuery('user');
$time = time();
$yesterday = $time - 60*60*24;
$new_user_count = $query->condition('created', $yesterday, '>=')
->count()
->execute();
// Handy when building up the conditions of a query, orConditionGroup() and andConditionGroup().
// Either allows you to define a group of conditions which will subsequently be either OR'ed or AND'ed together.
$query = \Drupal::entityQuery('node');
$group = $query->orConditionGroup()
->condition('uid', 22)
->condition('uid', 14)
->condition('uid.entity.name', 'admin');
$entity_ids = $query->condition('type', 'article')
->condition($group) -
->execute();