Merge pull request #8871 from kenjis/fix-model-casting-TypeError

fix: [Model] casting causes TypeError when finding no record
This commit is contained in:
kenjis 2024-05-10 10:42:58 +09:00 committed by GitHub
commit 069e13df5a
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 32 additions and 2 deletions

View File

@ -210,7 +210,7 @@ class Model extends BaseModel
$row = $builder->get()->getResult($this->tempReturnType);
}
if ($useCast) {
if ($useCast && $row !== null) {
$row = $this->convertToReturnType($row, $returnType);
$this->tempReturnType = $returnType;
@ -318,7 +318,7 @@ class Model extends BaseModel
$row = $builder->limit(1, 0)->get()->getFirstRow($this->tempReturnType);
if ($useCast) {
if ($useCast && $row !== null) {
$row = $this->convertToReturnType($row, $returnType);
$this->tempReturnType = $returnType;

View File

@ -43,6 +43,16 @@ final class DataConverterModelTest extends LiveModelTestCase
$this->seeInDatabase('user', ['name' => 'Sm9obiBTbWl0aA==']);
}
public function testFindAsArrayReturnsNull(): void
{
$this->createModel(UserCastsTimestampModel::class);
$this->db->table('user')->truncate();
$user = $this->model->find(1);
$this->assertNull($user);
}
/**
* @return int|string Insert ID
*/
@ -102,6 +112,16 @@ final class DataConverterModelTest extends LiveModelTestCase
$this->assertInstanceOf(Time::class, $users[1]['created_at']);
}
public function testFindAllAsArrayReturnsNull(): void
{
$this->createModel(UserCastsTimestampModel::class);
$this->db->table('user')->truncate();
$users = $this->model->findAll();
$this->assertSame([], $users);
}
private function prepareTwoRecords(): void
{
$this->prepareOneRecord();
@ -170,6 +190,16 @@ final class DataConverterModelTest extends LiveModelTestCase
$this->assertInstanceOf(Time::class, $user['created_at']);
}
public function testFirstAsArrayReturnsNull(): void
{
$this->createModel(UserCastsTimestampModel::class);
$this->db->table('user')->truncate();
$user = $this->model->first();
$this->assertNull($user);
}
public function testFirstAsObject(): void
{
$this->prepareTwoRecords();