Kannika
Kannika

Reputation: 2558

cakephp save update data from old data value + new value

I don't know the keyword to search with my problem. How to save update data of a field that already exist a value and I want to update it with additional value.

Here is an example cakephp :

$userData = array(
      'id' => $userId,
      'credit' => $newCredit // This will update only new credit
);
$this->User->save($userData);

If I use the normal query MySQL it would be like this :

mysql_query("UPDATE `users` SET `credit` = `credit` + '$newCredit' WHERE `id` = '$userId'");

You can see the normal SQL Query only one time to update with existing data of credit. I know I can do by use SELECT those data and do the operation in php, then UPDATE data back, but it'll be 2 times (SELECT, then UPDATE).

So can cakephp can do it at once? and how :D?

Upvotes: 1

Views: 2859

Answers (3)

cornelb
cornelb

Reputation: 6066

updateAll will work

$this->User->updateAll(
       array('credit' => "credit + $newCredit"),
       array('id' => $userId)
    );

Upvotes: 2

Dezigo
Dezigo

Reputation: 3256

Try this one:

$userData = array(
      'id' => $userId,
      'credit' => 'credit +'.$newCredit // old credit value + new credit value
);
$this->User->save($userData);

Or this:

$newCredit = 566;
$this->User->read(null, $userId);
$this->User->set('credit',$this->User->field('credit') + $newCredit);
$this->User->save();

Upvotes: 0

user3270303
user3270303

Reputation:

Try this......

   $user =  $this->User->read(null, $primary_key_id);
   $new_credit = $user['User']['credit'] + $add_new_value_of_credit;
   $this->User->id = $primary_key_id;
   $this->User->saveField('credit', $new_credit);

Upvotes: 1

Related Questions