2016-04-14 103 views
0

我需要更新由+ 1列的值时,新记录获得创建: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, 
       ]); 
      } 
    } 

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

+0

被归类为某种原因确切的错误消息或意外行为? – Shadow

+0

即时消息没有得到任何错误,但是,它不返回任何结果 – JKLM

+0

如果似乎最好在成功save()记录后更新计数器。 'if($ model-> save()){/ * update counter and redirec * /}' – SiZE

回答

1

尝试这样的:

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

+0

其不增加柜台 – JKLM

+0

你有没有为room_types创建模型?像CreateNoteings() –

+0

是它已经存在'$ types = new Roomtypes();'... updateCounter函数应该在模型获得保存后运行,因为我尝试'actionUpdate'它的工作正常,但不工作'actionCreate' – JKLM

0

你应该像下面的代码:

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