Yii2: not able to update column value by + 1

巧了我就是萌 提交于 2019-12-07 14:44:47

问题


I need to update column value by + 1 when new records get created :

public function actionCreate()
    {
        $model = new CreateBookings();
        if ($model->load(Yii::$app->request->post())) {
            Yii::$app->db->createCommand("UPDATE room_types SET total_booked = total_booked + 1 WHERE room_type = '$model->room_type' ")->execute();
            $model->save();
            return $this->redirect(['view', 'id' => $model->id]);
            } else {
                 return $this->render('create', [
                 'model' => $model,
                 ]);
            }
    }

What am I doing wrong please guide :)


回答1:


Try this:

 Yii::$app->db->createCommand("UPDATE room_types SET total_booked=total_booked+1 WHERE room_type = '$model->room_type' ")->execute();

OR

public function actionCreate()
    {
        $model = new CreateBookings();
        if ($model->load(Yii::$app->request->post())) {

    $RoomType = new room_types(); // room type replace with model name
    $RoomType->updateCounters(['total_booked' => 1]);

      $model->save();
            return $this->redirect(['view', 'id' => $model->id]);
        } else {
            return $this->render('create', [
                'model' => $model,
            ]);
        }
    }

Official link




回答2:


You should like the following codes:

    $post = \backend\models\Posts::find()->where(['postID' => 25])->one();
    $post->updateCounters(['total_booked' => 1]);


来源:https://stackoverflow.com/questions/36623067/yii2-not-able-to-update-column-value-by-1

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!