diff --git a/core/lib/Drupal/Core/Entity/Query/Sql/Query.php b/core/lib/Drupal/Core/Entity/Query/Sql/Query.php index 7e5db5b9a05cb7214961ea2822307c13cbec9151..cd357c1c2acf07e95efd4c36b35a519dba5bdb70 100644 --- a/core/lib/Drupal/Core/Entity/Query/Sql/Query.php +++ b/core/lib/Drupal/Core/Entity/Query/Sql/Query.php @@ -21,6 +21,13 @@ class Query extends QueryBase implements QueryInterface { */ protected $sqlQuery; + /** + * The Tables object for this query. + * + * @var \Drupal\Core\Entity\Query\Sql\TablesInterface + */ + protected $tables; + /** * An array of fields keyed by the field alias. * @@ -101,6 +108,9 @@ protected function prepare() { $simple_query = FALSE; } $this->sqlQuery = $this->connection->select($base_table, 'base_table', ['conjunction' => $this->conjunction]); + // Reset the tables structure, as it might have been built for a previous + // execution of this query. + $this->tables = NULL; $this->sqlQuery->addMetaData('entity_type', $this->entityTypeId); $id_field = $this->entityType->getKey('id'); // Add the key field for fetchAllKeyed(). diff --git a/core/tests/Drupal/KernelTests/Core/Entity/EntityQueryAggregateTest.php b/core/tests/Drupal/KernelTests/Core/Entity/EntityQueryAggregateTest.php index 9e8de3617360cd1acd27d0a3b504cf15c02cb14d..72db7f6f5975c011fd620321abe0058747a7bc6d 100644 --- a/core/tests/Drupal/KernelTests/Core/Entity/EntityQueryAggregateTest.php +++ b/core/tests/Drupal/KernelTests/Core/Entity/EntityQueryAggregateTest.php @@ -541,6 +541,38 @@ public function testAggregation() { } + /** + * Tests preparing a query and executing twice. + */ + public function testRepeatedExecution() { + $query = $this->entityStorage->getAggregateQuery() + ->groupBy('user_id'); + + $this->queryResult = $query->execute(); + $this->assertResults([ + ['user_id' => 1], + ['user_id' => 2], + ['user_id' => 3], + ]); + + $entity = $this->entityStorage->create([ + 'id' => 7, + 'user_id' => 4, + 'field_test_1' => 42, + 'field_test_2' => 68, + ]); + $entity->enforceIsNew(); + $entity->save(); + + $this->queryResult = $query->execute(); + $this->assertResults([ + ['user_id' => 1], + ['user_id' => 2], + ['user_id' => 3], + ['user_id' => 4], + ]); + } + /** * Asserts the results as expected regardless of order between and in rows. *