You are here

public function SelectComplexTest::testCountQueryGroupBy in Drupal 9

Same name and namespace in other branches
  1. 8 core/tests/Drupal/KernelTests/Core/Database/SelectComplexTest.php \Drupal\KernelTests\Core\Database\SelectComplexTest::testCountQueryGroupBy()

Tests that we can generate a count query from a query with GROUP BY.

File

core/tests/Drupal/KernelTests/Core/Database/SelectComplexTest.php, line 287

Class

SelectComplexTest
Tests the Select query builder with more complex queries.

Namespace

Drupal\KernelTests\Core\Database

Code

public function testCountQueryGroupBy() {
  $query = $this->connection
    ->select('test_task');
  $query
    ->addField('test_task', 'pid');
  $query
    ->groupBy('pid');
  $count = $query
    ->countQuery()
    ->execute()
    ->fetchField();
  $this
    ->assertEquals(3, $count, 'Counted the correct number of records.');

  // Use a column alias as, without one, the query can succeed for the wrong
  // reason.
  $query = $this->connection
    ->select('test_task');
  $query
    ->addField('test_task', 'pid', 'pid_alias');
  $query
    ->addExpression('COUNT([test_task].[task])', 'count');
  $query
    ->groupBy('pid_alias');
  $query
    ->orderBy('pid_alias', 'asc');
  $count = $query
    ->countQuery()
    ->execute()
    ->fetchField();
  $this
    ->assertEquals(3, $count, 'Counted the correct number of records.');
}