CodeIgniter4 icon indicating copy to clipboard operation
CodeIgniter4 copied to clipboard

How do you use `object` cast handler for Entity?

Open kenjis opened this issue 2 years ago • 4 comments

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

The object handler seems to expect the property to be set to an array. https://github.com/codeigniter4/CodeIgniter4/blob/0cd39937d7a8dbd8074237596024adce0fe3c2af/system/Entity/Cast/ObjectCast.php#L22-L25 https://github.com/codeigniter4/CodeIgniter4/blob/0cd39937d7a8dbd8074237596024adce0fe3c2af/tests/system/Entity/EntityTest.php#L439-L449

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?

kenjis avatar Sep 30 '23 00:09 kenjis

@iRedds seems to have created it.

In my opinion, the conversion is not necessary. If you want to convert an array, then it should be in the database as JSON and json, json-array should be used. The concept of an object is too big, therefore it requires a custom Cast

It's probably worth adding @deprecated and replacing saving and conversion with JSON

neznaika0 avatar Oct 08 '23 08:10 neznaika0

I have never used it. It is useless to me in the context of a relational database. Maybe for NoSQL or other scenarios, it might have some use.

michalsn avatar Oct 08 '23 13:10 michalsn

Yes, it seems useless in the context of a relational database.

But even for NoSQL, why don't you set an object to an entity, instead of an array?

kenjis avatar Oct 10 '23 01:10 kenjis

Good point. I honestly can't imagine a valid scenario 🤷‍♂️

michalsn avatar Oct 11 '23 11:10 michalsn