Hi,
I'm trying to cast an entity property into an array so that it autoserializes.
I'm using the constructor to fill the properties as follows
PHP Code:
<?php
namespace App\Entities;
use CodeIgniter\Entity;
class Submission extends Entity
{
protected $casts =[
'field2' => 'array'
];
}
<?php
$allowedFromPost = [
'field1'=>'value1',
'field2'=>[0,1],
];
$submission = new \App\Entities\Submission($allowedFromPost);
?>
Dumping the submission at this point (var_dump()) shows field2 being an array, it's not serialised.
Code:
["attributes":protected]=>
array(2) {
["field1"]=>
string(6) "value1"
["field2"]=>
array(2) {
[0]=>
int(0)
[1]=>
int(1)
}
}
if I do
PHP Code:
$allowedFromPost = [
'field1'=>'value1',
'field2'=>[0,1],
];
$submission = new \App\Entities\Submission($allowedFromPost);
$submission->field2 = $submission->field2;
and then var_dump, field2 is correctly serialised.
Code:
["attributes":protected]=>
array(2) {
["field1"]=>
string(6) "value1"
["field2"]=>
string(22) "a:2:{i:0;i:0;i:1;i:1;}"
}
For some reason, it seems like filling using the constructor does not autoserialize, I have to manually set the field. Am I doing something wrong?
The problem this caused is that when I tried insterting that into the Database, it threw an error saying "mysqli_sql_exception Operand should contain 1 column(s)" which went away when I flattened the array (first by dropping all but one values to test and then by using what I've done above)