0

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

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_id并且image_id等于NULL,为什么模型不能正确保存?

谢谢

4

1 回答 1

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;
于 2016-06-29T10:41:58.107 回答