Allow EntityQuery to be converted to the underlying SQL query

Created on 17 December 2020, almost 4 years ago
Updated 13 May 2023, over 1 year ago

Problem/Motivation

If you create an entity query for an entity type with SQL storage, the Drupal\Core\Entity\Query\Sql\Query class creates a regular SQL query object when the entity query's execute() is called.

There is no way to modify the SQL query from the entity query object.

Reasons you might want to do this include:

- JOINing to a non-entity table, e.g. πŸ› ContentEntity migration source doesn't consider the migration map Needs work
- making changes to the SQL query that the entity query class doesn't allow, such as doing $query->forUpdate(TRUE) to prevent concurrency when querying for entities

The only way to do this is:

1. Add a query tag to the entity query, e.g. $entity_query->addTag('my_tag');
2. Implement hook_query_TAG_alter() to then grab the SQL query once the entity query has built it, and it's about to be executed.

This isn't very good DX, as the code for extra bits you want to add to the SQL query is really far away from where you're building the entity query!

Steps to reproduce

Try it.

Proposed resolution

Option 1: Add a method to Drupal\Core\Entity\Query\Sql\Query that takes a callback that will then be applied to the SQL query in the finish() method. Callbacks would be applied in the order that they are registered on the entity query object.

Option 2: Add a toQuery() method, which returns the fully-built (non-Entity) SQL query object. This can then be added to with other statements, and then executed.

Remaining tasks

Write code.

User interface changes

None.

API changes

New method on the SQL entity query class.

Data model changes

None.

Release notes snippet

TODO

✨ Feature request
Status

Needs work

Version

10.1 ✨

Component
EntityΒ  β†’

Last updated about 4 hours ago

Created by

πŸ‡¬πŸ‡§United Kingdom joachim

Live updates comments and jobs are added and updated live.
  • Needs change record

    A change record needs to be drafted before an issue is committed. Note: Change records used to be called change notifications.

  • Needs subsystem maintainer review

    It is used to alert the maintainer(s) of a particular core subsystem that an issue significantly impacts their subsystem, and their signoff is needed (see the governance policy draft for more information). Also, if you use this tag, make sure the issue component is set to the correct subsystem. If an issue significantly impacts more than one subsystem, use needs framework manager review instead.

Sign in to follow issues

Comments & Activities

Not all content is available!

It's likely this issue predates Contrib.social: some issue and comment data are missing.

Production build 0.71.5 2024