Skip to main content
Blue Moose logo Blue Moose Field notes
← All articles
code

Drupal N+1: batch-load references across nodes

Rows of servers in a data center

I had a "latest articles" block on a Drupal site that looked innocent: fifty nodes, each showing its tags. In the query log it turned into a staircase of near-identical taxonomy_term_field_data lookups, one burst per node. Nothing was wrong with any single line of the template. The problem was that every node resolved its own references in isolation. Here is the pattern I use to collapse that into one extra query.

Why the loop is the problem

The naive version calls $node->get('field_tags')->referencedEntities() inside the loop. That method is smarter than it looks: per the API source, it collects the target IDs of that one field and makes a single loadMultiple() call. But it only knows about one field on one entity. Across 50 nodes you still get up to 50 separate loads, minus whatever the entity memory cache already holds.

The fix is to move the batching one level up: gather every target ID from every node first, load them all together, then look terms up from a plain array.

The service

<?php

namespace Drupal\my_module;

use Drupal\Core\Entity\EntityTypeManagerInterface;

/**
 * Builds teaser data for the latest articles without N+1 loads.
 */
final class ArticleTeaserBuilder {

  public function __construct(
    private readonly EntityTypeManagerInterface $entityTypeManager,
  ) {}

  /**
   * @return array<int, array{title: string, tags: string[]}>
   */
  public function build(int $limit = 50): array {
    $node_storage = $this->entityTypeManager->getStorage('node');
    $nids = $node_storage->getQuery()
      ->accessCheck(TRUE)
      ->condition('type', 'article')
      ->condition('status', 1)
      ->sort('created', 'DESC')
      ->range(0, $limit)
      ->execute();

    if (!$nids) {
      return [];
    }
    $nodes = $node_storage->loadMultiple($nids);

    // Pass 1: collect every referenced term ID, de-duplicated by key.
    $tids = [];
    foreach ($nodes as $node) {
      foreach ($node->get('field_tags') as $item) {
        if ($item->target_id !== NULL) {
          $tids[$item->target_id] = $item->target_id;
        }
      }
    }

    // One load for all terms. Guard the empty case: loadMultiple(NULL)
    // loads EVERY entity of that type, but an empty array loads none.
    $terms = $tids
      ? $this->entityTypeManager->getStorage('taxonomy_term')->loadMultiple($tids)
      : [];

    // Pass 2: assemble the result from the in-memory map.
    $rows = [];
    foreach ($nodes as $nid => $node) {
      $names = [];
      foreach ($node->get('field_tags') as $item) {
        $term = $terms[$item->target_id] ?? NULL;
        if ($term && $term->access('view')) {
          $names[] = $term->label();
        }
      }
      $rows[$nid] = ['title' => $node->label(), 'tags' => $names];
    }
    return $rows;
  }

}

Register it like any service, with arguments: ['@entity_type.manager'] in my_module.services.yml.

Details that matter

  • Key by ID to de-duplicate. Fifty articles share maybe a dozen tags, so the keyed array keeps the final IN (...) list short.
  • Keep the access check. Loading entities in bulk skips nothing, but it also grants nothing. I still call access('view') per term, because an unpublished term shouldn't leak its label just because I loaded it efficiently.
  • Don't pass NULL. The signature is loadMultiple(?array $ids = NULL), and the NULL default means "everything". An accidentally unset variable here would try to load the whole vocabulary.

When to use it, and the catch

I reach for this whenever a loop over entities touches the same reference field on each one: listings, feeds, export commands, search result decorators. Confirm the win with the query log (Devel or Webprofiler) before and after rather than trusting my arithmetic. I traced this code by hand and did not run it against a live site.

The catch is memory. Loading 5,000 nodes plus their references in one go will hurt, so chunk with array_chunk($nids, 100) in batch jobs. And if the output is rendered, cache tags on the block will usually matter more than shaving queries from an uncached build.

BM
Blue Moose
The moose behind Blue Moose. Full-stack PHP developer — Drupal by day, Symfony by night, tests always.