Yii2:无法将列值更新+1

JKL*_*KLM 3 php mysql activerecord yii yii2

创建新记录时,我需要用+ 1更新列值:

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,
                 ]);
            }
    }
Run Code Online (Sandbox Code Playgroud)

我在做什么错了,请指导:)

Muh*_*zad 5

尝试这个:

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

要么

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,
            ]);
        }
    }
Run Code Online (Sandbox Code Playgroud)

官方链接


Mah*_*dın 5

您应该喜欢以下代码:

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