Problem/Motivation

When executing an entity query (standard or aggregate) that queries the same field across multiple different entity reference relationships (e.g., querying field_start_station.entity.field_code and field_end_station.entity.field_code), the query builder incorrectly reuses the SQL table join alias from the first relationship instead of creating a separate join for the second relationship.

This is caused by a key collision inside Drupal\Core\Entity\Query\Sql\Tables. When traversing relationships, the query builder constructs a $next_index_prefix (e.g., "entity.target_id") but omits the name of the referencing field itself (e.g., "field_start_station"). Consequently, both fields end up with the identical lookup path "entity.target_id.field_code", causing the second field to fetch values from the first joined table instead of its own.

Steps to Reproduce

Scenario Setup (Core-only)

Consider a Drupal site with the following content types:

  1. Station (node bundle station):
    • Has a text field: field_code (e.g., station code "AMS", "CDG").
  2. Trip (node bundle trip):
    • Has an entity reference field: field_start_station (referencing a station node).
    • Has an entity reference field: field_end_station (referencing a station node).

The Entity Query

$query = \Drupal::entityTypeManager()->getStorage('node')->getAggregateQuery();
$query
  ->accessCheck(FALSE)
  ->condition('type', 'trip')
  ->groupBy('nid')
  ->aggregate('field_start_station.entity.field_code', 'MIN', NULL, 'min_start')
  ->aggregate('field_end_station.entity.field_code', 'MIN', NULL, 'min_end');

$results = $query->execute();

Proposed Resolution

To fix the issue, the field/relationship $specifier must be prepended to the $next_index_prefix when preparing the relationship path, both for dedicated table storages and shared table properties inside Drupal\Core\Entity\Query\Sql\Tables::addField().

Issue fork drupal-3591419

Command icon Show commands

Start within a Git clone of the project using the version control instructions.

Or, if you do not have SSH keys set up on git.drupalcode.org:

  • 3591419-entity-query Comparecompare
  • main Comparecompare
  • 1 hidden branch
  • 3591419-Entity-query-alias Comparecompare

Comments

pjcarly created an issue.

ishani patel made their first commit to this issue’s fork.

ishani patel changed the visibility of the branch 3591419-Entity-query-alias to hidden.