Using entity.query for custom entity queriesfor Drupal 8 , 9 , 10 , and 11

Last updated :  

Introduction

Having structured our custom entities with fields and handlers, today’s focus is on how you interact with these entities using entity.query. Querying is a critical skill in Drupal development, necessary for manipulating and analyzing data stored in entities. Drupal's entity.query provides a robust and flexible mechanism for constructing dynamic queries without writing SQL.

Why Use Entity Query?

Drupal's entity.query API comes loaded with several advantages for developers:

  • Database Abstraction: Allows for complex queries without direct SQL, ensuring compatibility and security across different database systems.
  • Flexibility: Offers a fluent interface for building queries, making it easier to chain multiple conditions and commands.
  • Performance: Efficiently handles large datasets by leveraging Drupal's caching and backend optimizations.

Getting Started with Entity Query

The entity.query service lets you construct a query in a straightforward manner. Let’s begin by writing a basic query to fetch our Contact Messages.

Fetching All Entities

To begin, here's how to retrieve all entities of a specific type:

$query = \Drupal::entityQuery('contact_message');
$entity_ids = $query->execute();

This simple query retrieves all Contact Message entity IDs in your database.

Adding Conditions

Often, you'll need to filter results based on certain criteria. Here's how you might only retrieve messages submitted within the last month:

$query = \Drupal::entityQuery('contact_message')
  ->condition('submitted', strtotime('-1 month'), '>=');
$recent_entity_ids = $query->execute();

Using the condition method, you can compare against field values, supporting operators like =, !=, <, <=, >, and >=.

Complex Queries with AND/OR Conditions

Constructing more complex queries often requires logical "AND" and "OR". Entity queries support this using andConditionGroup() or orConditionGroup():

$query = \Drupal::entityQuery('contact_message')
  ->condition('email', 'example@domain.com')
  ->condition('submitted', time(), '<')
  ->orConditionGroup()
    ->condition('name', 'John Doe')
    ->condition('name', 'Jane Doe');
$custom_entity_ids = $query->execute();

This example retrieves messages from example@domain.com before the current time or those named John or Jane Doe.

Sorting and Ranges

Entity queries also encompass sorting results and defining limited ranges:

Sorting Results

Sort returned results by adding a sort condition:

$query = \Drupal::entityQuery('contact_message')
  ->sort('submitted', 'DESC');
$sorted_ids = $query->execute();

This snippet sorts results based on the submitted timestamp, in descending order.

Limiting Results

To restrict the number of entities retrieved, use range:

$query = \Drupal::entityQuery('contact_message')
  ->range(0, 10);
$limited_entity_ids = $query->execute();

This query limits retrieval to the first ten contact message entity IDs.

Practical Example

Let’s build a useful example applying what we've learned. Suppose you're creating an admin report page listing all recent, unread contact messages.

$query = \Drupal::entityQuery('contact_message')
  ->condition('status', 0) // Unread messages
  ->condition('submitted', strtotime('-1 week'), '>=')
  ->sort('submitted', 'DESC')
  ->range(0, 20);
$unread_messages_ids = $query->execute();
$unread_messages = \Drupal::entityTypeManager()->getStorage('contact_message')->loadMultiple($unread_messages_ids);

This retrieves unread messages from the past week, showing them in order of latest to earliest, capped at twenty entries.

Conclusion

Leveraging entity.query in Drupal empowers developers to perform intricate querying tasks with relative ease. By understanding and utilizing these capabilities, you can effectively extract and manipulate your entity data, gaining valuable insights and creating dynamic user experiences.

Next Lesson Teaser

Having grasped querying within Drupal, our upcoming lesson will explore how to render entity queries within controllers to output dynamic pages and data. This is where the real magic happens with Drupal! Stay curious!