问题
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