Yii2:无法将列值更新+ 1

时间:2016-04-14 12:25:59

标签: 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,
                 ]);
            }
    }

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

2 个答案:

答案 0 :(得分:4)

试试这个:

 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,
            ]);
        }
    }

官方link

答案 1 :(得分:3)

您应该喜欢以下代码:

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