Con*_*kas 5 php codeigniter codeigniter-4
我试图将一个实体属性转换为一个数组,以便它自动序列化。
实体设置如下
\App\Entities\Submission.php
<?php
namespace App\Entities;
use CodeIgniter\Entity;
class Submission extends Entity
{
protected $casts =[
'field2' => 'array'
];
}
Run Code Online (Sandbox Code Playgroud)
然后在控制器中创建一个新实体,使用构造函数填充它
<?php
$allowedFromPost = [
'field1'=>'value1',
'field2'=>[0,1],
];
$submission = new \App\Entities\Submission($allowedFromPost);
?>
Run Code Online (Sandbox Code Playgroud)
此时转储提交 (var_dump()) 显示 field2 是一个数组,它没有被序列化。
["attributes":protected]=>
array(2) {
["field1"]=>
string(6) "value1"
["field2"]=>
array(2) {
[0]=>
int(0)
[1]=>
int(1)
}
}
Run Code Online (Sandbox Code Playgroud)
如果我做
<?php
$allowedFromPost = [
'field1'=>'value1',
'field2'=>[0,1],
];
$submission = new \App\Entities\Submission($allowedFromPost);
?>
Run Code Online (Sandbox Code Playgroud)
然后 var_dump, field2 被正确序列化。
["attributes":protected]=>
array(2) {
["field1"]=>
string(6) "value1"
["field2"]=>
string(22) "a:2:{i:0;i:0;i:1;i:1;}"
}
Run Code Online (Sandbox Code Playgroud)
出于某种原因,使用构造函数填充似乎不会自动序列化,我必须手动设置该字段。难道我做错了什么?
这导致的问题是,当我尝试将该实体插入数据库时,它抛出了一个错误说
“
mysqli_sql_exception Operand should contain 1 column(s)”
当我展平数组时它消失了(首先通过删除除一个值之外的所有值进行测试,然后使用我在上面所做的操作)
================
编辑 11/05:结果证明这是核心代码的问题。fill()(和构造函数)未配置为使用,__set()因此未发生自动序列化。请在此处查看 Codeigniter 的 Github 页面上的 PR 。
我会接受 Kulshreshth K 的回答,因为就目前而言,这提供了足够的解决方法,但将来很可能不需要它。
将其添加到您的实体中:
public function __construct($arr) {
$this->field2 = $arr['field2'];
}
Run Code Online (Sandbox Code Playgroud)
控制器:
$allowedFromPost = [
'field1'=>'value1',
'field2'=>[0,1],
];
$submission = new \App\Entities\Submission($allowedFromPost);
var_dump($submission)
Run Code Online (Sandbox Code Playgroud)
结果:
["attributes":protected]=>
array(2) {
["field1"]=>
string(6) "value1"
["field2"]=>
string(22) "a:2:{i:0;i:0;i:1;i:1;}"
}
Run Code Online (Sandbox Code Playgroud)
根据 CI 文档,无论如何,您都需要在初始化其模型后设置它:
<?php namespace App\Entities;
use CodeIgniter\Entity;
class User extends Entity
{
protected $casts => [
'options' => 'array',
'options_object' => 'json',
'options_array' => 'json-array'
];
}
$user = $userModel->find(15);
$options = $user->options;
$options['foo'] = 'bar';
$user->options = $options;
$userModel->save($user);
Run Code Online (Sandbox Code Playgroud)