2016-04-14 71 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]);