Yii2多个模型循环保存错误

时间:2016-06-29 10:07:22

标签: php activerecord yii2 yii2-advanced-app yii2-model

我有一张表,我必须保存多个数据,在我的控制器中我实现了这个动作:

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;
}

收到的数据是正确的,但不是结果,该操作唯一的做法是添加slider_idimage_id等于NULL的新表格行,为什么模型不会保存不正确吗?

由于

1 个答案:

答案 0 :(得分:0)

事情是你打电话

$model::find()->where(['slider_id' => $id, 'image_id' => $key])->all()

您不能更改$model对象本身。基本上你在打电话:

SlidersImages::find()->where(['slider_id' => $id, 'image_id' => $key])->all()

因此,稍后当您致电$model->save()时,您正在保存具有空属性的$model对象(您只更改了display_order

我的建议:尝试将->all()调用的结果分配给新的var,然后使用它:

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;