Skip to content

How do you use object cast handler for Entity? #7993

Open
@kenjis

Description

@kenjis

https://codeigniter4.github.io/CodeIgniter4/models/entities.html#property-casting

The object handler seems to expect the property to be set to an array.

public static function get($value, array $params = []): object
{
return (object) $value;
}

public function testCastObject(): void
{
$entity = $this->getCastEntity();
$data = ['foo' => 'bar'];
$entity->sixth = $data;
$this->assertIsObject($entity->sixth);
$this->assertInstanceOf('stdClass', $entity->sixth);
$this->assertSame($data, (array) $entity->sixth);
}

However, when setting an array, we cannot save that Entity to the database.

        $entity = new class () extends Entity {
            protected $casts = [
                'id'     => 'int',
                'active' => 'int-bool',
                'memo'   => 'object', // Use `object` handler
            ];
        };
        $model = new class () extends Model {
            protected $table         = 'users';
            protected $allowedFields = [
                'username', 'active', 'memo',
            ];
            protected $useTimestamps = true;
        };
        $entity->fill(['username' => 'johnsmith', 'active' => false, 'memo' => ['foo', 'bar']]);
        $model->save($entity); // CodeIgniter\Database\Exceptions\DatabaseException : Operand should contain 1 column(s)

How is this handler used in the first place?

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions