php - Yii2 multiple models loop save error

664

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

406

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:

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;

People are also looking for solutions to the problem: php - Update sub fields from repeater with different values in WordPress ACF

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.