CakePHP: add / subtract using save ()?

I am trying to simply execute the following Cake save () functions.

UPDATE user SET value = value-1 

However, it looks like it can only be installed. He will not understand anything that I pass to him to increase or subtract, and no one from the Internet seems to have this problem .: P Even when you look at the full part of the software created on CakePHP 2.0, I find $ this-> query (), which is used to update in increments! Is it really how I will update if I don't have a value to configure yet?

(the code is as follows)

  $data = array('id' => uid, 'value' => "Users.value = Users.value - 1"); $this->User->save($data); 
+4
source share
3 answers

The code to create the increment or decrement in the CakePHP database is as follows:

 $this->User->updateAll(array('value' => 'value - 1'), array('id' => uid)); 

Arun's answer was wrong; you must put the value -1 in quotation marks so that Cake recognizes that it is part of the request. Otherwise, it will try to set -1 for all User.value. Note that you must put the information (identifiers) of the columns that you want to update in the second condition.

+3
source

basically you just need to use updateAll for atomic queries like

 $this->User->updateAll($fields, $conditions); 

http://book.cakephp.org/2.0/en/models/saving-your-data.html#model-updateall-array-fields-array-conditions

+1
source

You can do this using the following query:

 $this->User->updateAll(array('User.value' => 'User.value' - 1)); //or //$this->User->updateAll(array('User.value' => 'User.value' - 1), array('User.id' => $uid)); 
-1
source

All Articles