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

Abdul Hameed
  • 263
  • 4
  • 19
MarBer
  • 535
  • 1
  • 5
  • 22

1 Answers1

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;
Ruslan Bes
  • 2,715
  • 2
  • 25
  • 32
  • 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; }` – MarBer Jun 29 '16 at 11:34