0

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 with slider_id and image_id equal to NULL, why the model doesn't save correctly?

Thanks

1 Answer 1

0

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 changed display_order)

My advise here: try to assign the result of the ->all() call to the new var and then work with it:

public function actionUpdateOrder($id){
    /*DA TESTARE*/
    //$result = 0;
    $result = true;
    $s = new Session;
    if ($new_order = Yii::$app->request->post('order')) {
        //$s['us_model'] = 0;
        foreach ($new_order as $key => $value) {
            $models = SliderImages::find()->where(['slider_id' => $id, 'image_id' => $key])->all();
            if (count($models)) {
                // loop through $models and update them
            }
        }
    }

    return $result;
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks @Ruslan Bes for the answer, the final solution I've adopted using your suggestion is as follows: if ($model = SlidersImages::findOne(['slider_id' => $id, 'image_id' => $key])) { $model->display_order = $value; //$result = ($t = $model->update()) ? $result + $t : $result; $result = $model->save() && $result; }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.