The above screenshot from phpmyadmin. I saving the data by the code below:
// In the update action:
//...
if ($flag) {
$transaction->commit();
Yii::$app->getSession()->setFlash('success', 'Record has been updated!');
$this->savedi($model);
return $this->redirect(['view', 'id' => $model->id]);
}
//...
private function savedi($model)
{
$output = [];
foreach ($model->invoiceItems as $i => $item){
$output['items'][$i]['id'] = $item->item_id;
$output['items'][$i]['title'] = $item->item->title;
$output['items'][$i]['qty'] = $item->qty;
}
$model->saved = json_encode($output);
$model->save();
}
I don't know why the JSON is corrupted like that?
CodePudding user response:
The string in question looks like double encoded JSON.
The yii2 has some basic support for JSON fields which take care of encoding/decoding. So instead of calling json_encode()
yourself you just need to assign array/object that should be encoded as it is.
private function savedi($model)
{
$output = [];
foreach ($model->invoiceItems as $i => $item){
$output['items'][$i]['id'] = $item->item_id;
$output['items'][$i]['title'] = $item->item->title;
$output['items'][$i]['qty'] = $item->qty;
}
$model->saved = $output;
$model->save();
}