function FetchTest::testQueryFetchClasstype

Same name in other branches
  1. 8.9.x core/tests/Drupal/KernelTests/Core/Database/FetchTest.php \Drupal\KernelTests\Core\Database\FetchTest::testQueryFetchClasstype()
  2. 10 core/tests/Drupal/KernelTests/Core/Database/FetchTest.php \Drupal\KernelTests\Core\Database\FetchTest::testQueryFetchClasstype()

Confirms that we can fetch a record into a new instance of a custom class.

The name of the class is determined from a value of the first column.

See also

\Drupal\Tests\system\Functional\Database\FakeRecord

File

core/tests/Drupal/KernelTests/Core/Database/FetchTest.php, line 107

Class

FetchTest
Tests the Database system's various fetch capabilities.

Namespace

Drupal\KernelTests\Core\Database

Code

public function testQueryFetchClasstype() {
    $records = [];
    $result = $this->connection
        ->query('SELECT [classname], [name], [job] FROM {test_classtype} WHERE [age] = :age', [
        ':age' => 26,
    ], [
        'fetch' => \PDO::FETCH_CLASS | \PDO::FETCH_CLASSTYPE,
    ]);
    foreach ($result as $record) {
        $records[] = $record;
        $this->assertInstanceOf(FakeRecord::class, $record);
        $this->assertSame('Kay', $record->name);
        $this->assertSame('Web Developer', $record->job);
        $this->assertFalse(isset($record->classname), 'Classname field not found, as intended.');
    }
    $this->assertCount(1, $records, 'There is only one record.');
}

Buggy or inaccurate documentation? Please file an issue. Need support? Need help programming? Connect with the Drupal community.