4

I'm trying to simply perform the following via Cake's save() function.

UPDATE user SET value = value-1

However, it seems it can only set. It will not understand anything I pass to it to increment or subtract, and no one on the internet seems to be having this issue. :P Even when going through a full piece of software someone built on CakePHP 2.0, I'm finding $this->query() used for updating by increments! Is this really how I'll update if I don't already have the value to be setting?

(code appears as follows)

 $data = array('id' => uid, 'value' => "Users.value = Users.value - 1");
 $this->User->save($data);
Vael Victus
  • 3,966
  • 7
  • 34
  • 55
  • What's the query it's generating? (THAT is what you should be looking at - what have you attempted, and what queries were generated from each attempt?) – Dave Aug 09 '12 at 12:30
  • Can't you just decrement Users.value before putting it in that array? – Andrei Cristian Prodan Aug 09 '12 at 12:31
  • I don't know what users.value is in this case, however, to decrement from to set the value. Dave, I'll work on that, seems my normal method of killing find() doesn't apply to save. – Vael Victus Aug 09 '12 at 12:43
  • some kind of duplicate of http://stackoverflow.com/questions/8773457/cakephp-increment-value etc – mark Aug 09 '12 at 12:45

3 Answers3

3

The code for producing an increment or decrement in CakePHP database is as follows:

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

Arun's answer was not correct; you must put the - 1 within quotes to get Cake to recognize it is part of the query. Else it will try to set all User.value to -1. Note that you must put the information (identifiers) of the columns that you want to update on in the second condition.

Vael Victus
  • 3,966
  • 7
  • 34
  • 55
1

basically you just have to use updateAll for atomic queries like this

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

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

mark
  • 21,691
  • 3
  • 49
  • 71
-1

You can do so using 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));
Arun Jain
  • 5,476
  • 2
  • 31
  • 52
  • Hi Mark, Have you seen the first statement of question? I think the question has 2 points, one is `update` and second is `update with where clause`. I think @arun missed another point. – Arun Jain Aug 10 '12 at 14:01
  • I think he just wanted to emphasize the increment part. therefore the two code parts. but all in all its always with the condition (which would make most sense anyway). – mark Aug 12 '12 at 20:55
  • As Vael has noted: "Arun's answer was not correct; you must put the - 1 within quotes" – Simon East Dec 20 '12 at 06:24