function SelectComplexTest::testGroupBy
Same name in other branches
- 9 core/tests/Drupal/KernelTests/Core/Database/SelectComplexTest.php \Drupal\KernelTests\Core\Database\SelectComplexTest::testGroupBy()
- 8.9.x core/tests/Drupal/KernelTests/Core/Database/SelectComplexTest.php \Drupal\KernelTests\Core\Database\SelectComplexTest::testGroupBy()
- 11.x core/tests/Drupal/KernelTests/Core/Database/SelectComplexTest.php \Drupal\KernelTests\Core\Database\SelectComplexTest::testGroupBy()
Tests GROUP BY clauses.
File
-
core/
tests/ Drupal/ KernelTests/ Core/ Database/ SelectComplexTest.php, line 78
Class
- SelectComplexTest
- Tests the Select query builder with more complex queries.
Namespace
Drupal\KernelTests\Core\DatabaseCode
public function testGroupBy() : void {
$query = $this->connection
->select('test_task', 't');
$count_field = $query->addExpression('COUNT([task])', 'num');
$task_field = $query->addField('t', 'task');
$query->orderBy($count_field);
$query->groupBy($task_field);
$this->assertMatchesRegularExpression("/ORDER BY .*[^\\w\\s]num[^\\w\\s]/", (string) $query);
$this->assertMatchesRegularExpression("/GROUP BY .*[^\\w\\s]task[^\\w\\s]/", (string) $query);
$result = $query->execute();
$num_records = 0;
$last_count = 0;
$records = [];
// Verify that the results are returned in the correct order.
foreach ($result as $record) {
$num_records++;
$this->assertGreaterThanOrEqual($last_count, $record->{$count_field});
$last_count = $record->{$count_field};
$records[$record->{$task_field}] = $record->{$count_field};
}
$correct_results = [
'eat' => 1,
'sleep' => 2,
'code' => 1,
'found new band' => 1,
'perform at superbowl' => 1,
];
foreach ($correct_results as $task => $count) {
$this->assertEquals($count, $records[$task], "Correct number of '{$task}' records found.");
}
$this->assertEquals(6, $num_records, 'Returned the correct number of total rows.');
}
Buggy or inaccurate documentation? Please file an issue. Need support? Need help programming? Connect with the Drupal community.