3 namespace Drupal\workspaces\EntityQuery;
5 use Drupal\Core\Entity\Query\Sql\Query as BaseQuery;
8 * Alters entity queries to use a workspace revision instead of the default one.
10 class Query extends BaseQuery {
13 prepare as traitPrepare;
17 * Stores the SQL expressions used to build the SQL query.
19 * The array is keyed by the expression alias and the values are the actual
23 * An array of expressions.
25 protected $sqlExpressions = [];
30 public function prepare() {
31 $this->traitPrepare();
33 // If the prepare() method from the trait decided that we need to alter this
34 // query, we need to re-define the the key fields for fetchAllKeyed() as SQL
36 if ($this->sqlQuery->getMetaData('active_workspace_id')) {
37 $id_field = $this->entityType->getKey('id');
38 $revision_field = $this->entityType->getKey('revision');
40 // Since the query is against the base table, we have to take into account
41 // that the revision ID might come from the workspace_association
42 // relationship, and, as a consequence, the revision ID field is no longer
43 // a simple SQL field but an expression.
44 $this->sqlFields = [];
45 $this->sqlExpressions[$revision_field] = "COALESCE(workspace_association.target_entity_revision_id, base_table.$revision_field)";
46 $this->sqlExpressions[$id_field] = "base_table.$id_field";
55 protected function finish() {
56 foreach ($this->sqlExpressions as $alias => $expression) {
57 $this->sqlQuery->addExpression($expression, $alias);
59 return parent::finish();