Drupalwoo ☉

Fetch Drupal data with EntityQuery conditions

Drupal’s EntityQuery API gives module code a structured way to retrieve entities that match specific conditions. It is useful when a custom feature needs articles, users, taxonomy terms or another entity type filtered by content type, publication state, author, language, date or identifier.

The query returns matching entity IDs, not complete objects. You execute it, then load those IDs through the relevant entity storage. Separating those stages keeps filtering lightweight and provides an explicit place to handle access. For Australian teams handling personal information under the Australian Privacy Act, retaining Drupal’s access-aware defaults is a sensible security baseline, though compliance also depends on the wider site configuration.

A reliable pattern is to define the entity type, add conditions, execute, load and then present the results. Australia’s Drupal community has a strong history of local meetups and events in Melbourne, Sydney and Canberra, where these core patterns are shared between developers, agencies and site builders.

Approach Entity definition properties Custom field values Access handling Strongest use
EntityQuery Yes Generally no Yes, by default Module and service code
Views Yes Yes Configurable Admin-managed listings
Database query No abstraction Schema-dependent Not automatic Migrations and reporting
Entity storage load Exact IDs only Not a filter No list-level filtering Fetching known entities

Understand what EntityQuery returns

Start with the entity type ID, such as node, user or taxonomy_term. EntityQuery works with entity properties exposed by Drupal’s entity definitions; it is not a general-purpose query builder for every database column. A node query can filter machine-readable content types and publication state, while a term query uses different properties. Inspecting the entity definition prevents conditions against keys that the chosen type does not provide.

Build the smallest query that expresses the requirement:

$query = \Drupal::entityQuery('node')
  ->accessCheck(TRUE)
  ->condition('type', 'article')
  ->condition('status', 1);

$ids = $query->execute();

The status condition selects published article nodes, while access checking is applied when the query executes. If untranslated or unpublished content should also be returned, make that decision deliberately.

The result of execute() is an array of entity IDs. Load them with the storage for that type because IDs alone cannot expose full field values or labels. In injectable service code, use the entity_type.manager service and call getStorage('node'); static \Drupal calls keep these examples short.

Choose properties and operators carefully

Every condition names a property and supplies a value, with = as the default operator. Common node properties include type for the bundle, status, uid, langcode, created and changed. Other entity types expose different keys, so status or uid should not be assumed to exist everywhere. The label key is also available only when the entity definition defines it.

Choose an operator that matches the data rather than filtering after loading:

A practical condition set might look like this:

$query
  ->condition('uid', $author_id)
  ->condition('created', $cutoff, '>=')
  ->condition('type', ['article', 'news'], 'IN');

Date properties such as created and changed use Unix timestamps, not formatted strings. That matters for Australian sites: a Sydney newsroom and a Melbourne office can sit on different daylight-saving offsets during AEDT and AEST, while Drupal stores the timestamp consistently. Convert the intended local cutoff to a timestamp before comparing it, then format the result for display. Editors may expect 14/03/2026, even when developers log ISO 8601.

Combine filters with AND and OR logic

Conditions are combined with AND by default. Adding type = article and status = 1 means both must match, which is usually the safest interpretation. The following query also restricts language and publication state, then sorts the newest content first.

$query = \Drupal::entityQuery('node')
  ->condition('type', 'article')
  ->condition('status', 1)
  ->condition('langcode', 'en')
  ->condition('created', $cutoff, '>=')
  ->sort('created', 'DESC');

Use an OR group when either value is acceptable. This example returns an article or an event, but only when the node is published:

use Drupal\Core\Entity\Query\ConditionGroupInterface;

$query
  ->condition('status', 1)
  ->conditionGroup(ConditionGroupInterface::OR)
    ->condition('type', 'article')
    ->condition('type', 'event');

Keep nested groups shallow enough that their meaning remains obvious. These patterns cover most editorial filtering requirements:

Respect access checks and revision scope

Entity access checks are enabled unless accessCheck(FALSE) is set explicitly. Keep them enabled for requests driven by editors or visitors because an access-aware query should not become a way around unpublished content or entity-level permissions. If a migration or tightly controlled administrative job needs otherwise, disable the check only inside code that has its own trusted authorisation boundary and a clearly defined scope.

Revisionable types also require a decision about which revisions to query. Core query methods such as allRevisions() and latestRevision() alter that scope, while ordinary queries normally concern the entity’s current revision. Do not request every revision merely to display a current listing: it multiplies results and can surface draft or superseded content that the interface never intended to show.

Access checking and revision selection solve different problems. Access control asks whether the entity may be considered in the current context; revision scope asks which version is being tested. Document both decisions near the query, especially in scheduled jobs where no browser session supplies an obvious permission context. That matters during an Australian agency handover, when a module may move from a developer sandbox to a client’s live environment.

Filter custom fields through the right layer

A crucial limitation is that core EntityQuery conditions generally target entity definition properties, not the stored values of ordinary custom fields. Asking for a field such as field_event_date in condition() is therefore not a dependable field-value filter. The node’s type, status, author and timestamps remain straightforward; the value inside a multi-value field lives in field storage and may occupy several rows.

Choose a layer designed for that value. Views can build an admin-managed listing with field filters. Search API is suited to indexed content and faceted discovery, while a GraphQL or custom query service can expose deliberate field filters. A direct database query can also work, but its joins, base tables and cardinality must match the installed field configuration. Database code is rarely a drop-in replacement for entity access and should be reserved for controlled reporting or migration tasks.

A hybrid is sometimes sensible: EntityQuery narrows candidates by type, status and date, then the loaded entities are inspected for the custom value. That is efficient only when the first filter leaves a small set. For broad collections, filtering inside memory becomes wasteful and can produce inconsistent results when the candidate list is too large. Prefer a field-aware query, then convert the selected IDs back into entities for consistent field access.

Load, paginate, and test the result

Load the returned IDs through the same entity type used in the query:

$storage = \Drupal::entityTypeManager()->getStorage('node');
$entities = $storage->loadMultiple($ids);

loadMultiple() returns entities keyed by ID. Its array order is not a substitute for query sorting, so reorder it against the original ID list when display order matters. Loading by ID does not apply another list-level access filter, which is another reason to keep the original access-aware query intact.

For pagination, count the matching IDs and apply a range to the result query. Keep the two operations aligned, including identical conditions, access settings and revision scope:

$count_query = clone $query;
$total = $count_query->count();

$query->range($offset, $limit);
$ids = $query->execute();

This prevents an unbounded load. Sorting should be stable for pagination, so add a secondary ID sort where duplicate timestamps are possible.

Test the query with published and unpublished content, empty values, several bundles, different languages and a user who lacks access. Kernel or functional tests should execute it against real test entities. Keep logging free of personal content and record only counts, filters and timings. During the final “go live” run used by Australian agencies, compare the selected IDs with an editorial report; that catches bundle-name, timezone and permission mistakes before the site is handed over.