Hello,
I have a database table which has 1 field that stores JSON. In my model, the variable which is turned into json is an array. Using the beforeSave
method, I json_encode
the array for storage in the database.
What I need to do is when an existing record is fetched from the database, automatically json_decode
it back into an array.
For example:
$model->myValue = [
'array1' => [
'key1' => 'value1',
'key2' => 'value2'
]
];
$model->save(); // This triggers beforeSave, json encoding the array.
// Now, when I retrieve a value, it should be automatically decoded:
$model = MyModel::findFirst();
echo $model->myValue['array']['key1']; // Outputs value1
This attempt to decode the value of the variable would of course only need to run when fetching an existing record, not always when an object of that model is instantiated (example: new MyModel()).
So, does anyone know how I can accomplish this? Thanks