Yii2:无法按 + 1 更新列值

2022-01-04 00:00:00 php mysql yii2 yii activerecord

我需要在创建新记录时将列值更新为 + 1 :

公共函数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();返回 $this->redirect(['view', 'id' => $model->id]);} 别的 {返回 $this->render('create', ['模型' =>$模型,]);}}

我做错了什么请指导:)

解决方案

试试这个:

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

公共函数actionCreate(){$model = new CreateBookings();if ($model->load(Yii::$app->request->post())) {$RoomType = new room_types();//房间类型替换为模型名称$RoomType->updateCounters(['total_booked' => 1]);$model->save();返回 $this->redirect(['view', 'id' => $model->id]);} 别的 {返回 $this->render('create', ['模型' =>$模型,]);}}

官方链接

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 :)

解决方案

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

相关文章