function SelectComplexTest::testGroupByAndHaving

Same name in other branches
  1. 8.9.x core/tests/Drupal/KernelTests/Core/Database/SelectComplexTest.php \Drupal\KernelTests\Core\Database\SelectComplexTest::testGroupByAndHaving()
  2. 10 core/tests/Drupal/KernelTests/Core/Database/SelectComplexTest.php \Drupal\KernelTests\Core\Database\SelectComplexTest::testGroupByAndHaving()
  3. 11.x core/tests/Drupal/KernelTests/Core/Database/SelectComplexTest.php \Drupal\KernelTests\Core\Database\SelectComplexTest::testGroupByAndHaving()

Tests GROUP BY and HAVING clauses together.

File

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

Class

SelectComplexTest
Tests the Select query builder with more complex queries.

Namespace

Drupal\KernelTests\Core\Database

Code

public function testGroupByAndHaving() {
    $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);
    $query->having('COUNT([task]) >= 2');
    $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(2, $record->{$count_field});
        $this->assertGreaterThanOrEqual($last_count, $record->{$count_field});
        $last_count = $record->{$count_field};
        $records[$record->{$task_field}] = $record->{$count_field};
    }
    $correct_results = [
        'sleep' => 2,
    ];
    foreach ($correct_results as $task => $count) {
        $this->assertEquals($count, $records[$task], new FormattableMarkup("Correct number of '@task' records found.", [
            '@task' => $task,
        ]));
    }
    $this->assertEquals(1, $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.