codeigniter4 / codeigniter4/CodeIgniter4

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

未关闭
#7,993 4 条评论 0 个 reaction 已指派 0 人 在 GitHub 查看
question
主要语言
PHP
星标
6k
派生
2k
平均合并
1 天 11 小时
30 天内合并 PR
73

描述

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.

```php
$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?

贡献指南

打开贡献指南

调研方向

先从 property casting 文档开始,然后阅读 system/Entity/Cast/ObjectCast.php 以及其中引用的 EntityTest.php 用例。复现使用 object cast 保存 Entity 的示例,并确定预期行为;当 handler 的使用方式和数据库交互都由明确的测试或文档更新覆盖时,即表示完成。

由索引模型根据 Issue 内容生成。

评估

技术栈
php
领域
backend, database
Issue 类型
缺陷
难度
3/5
预计耗时
1-2 天
活跃度
停滞
描述清晰度
基本清楚
新手友好度
35/100

把新 issue 发到你的邮箱

精选适合新手参与的 GitHub issue 摘要。