php - Yii2 multiple models loop save error
I've a table in which I have to save multiple data, in my controller I've implemented this action:
public function actionUpdateOrder($id){
/*DA TESTARE*/
//$result = 0;
$result = true;
$s = new Session;
$model = new SlidersImages();
if ($new_order = Yii::$app->request->post('order')) {
//$s['us_model'] = 0;
foreach ($new_order as $key => $value) {
if ($model::find()->where(['slider_id' => $id, 'image_id' => $key])->all()) {
$s['image_'.$key] = $model;
$model->display_order = $value;
//$result = ($t = $model->update()) ? $result + $t : $result;
$result = $model->save() && $result;
}
}
}
return $result;
}
The data received are right but not the result, the only thing that the action do is to add new table row withslider_id
andimage_id
equal toNULL
, why the model doesn't save correctly?
Thanks
Answer
Solution:
The thing is when you call
$model::find()->where(['slider_id' => $id, 'image_id' => $key])->all()
you don't change the
$model
object itself. Essentially you are calling:SlidersImages::find()->where(['slider_id' => $id, 'image_id' => $key])->all()
So, later when you call
$model->save()
you are saving a$model
object with empty attributes (you only changeddisplay_order
)My advise here: try to assign the result of the
->all()
call to the new var and then work with it: