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:
- Station (
nodebundlestation):- Has a text field:
field_code(e.g., station code "AMS", "CDG").
- Has a text field:
- Trip (
nodebundletrip):- Has an entity reference field:
field_start_station(referencing astationnode). - Has an entity reference field:
field_end_station(referencing astationnode).
- Has an entity reference field:
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().
| Comment | File | Size | Author |
|---|---|---|---|
| drupal-core-tables-alias-collision.patch | 1.22 KB | pjcarly |
Issue fork drupal-3591419
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
compare
- main
compare
- 3591419-Entity-query-alias
compare
Comments