UPDATE query with CakePHP

I know what I can use $this->Model->save()to update a specific record if I pass an identifier, but how can I update a single field on this line?

I have a table userswith a field balance. I want to update a field balancebased on what already exists.

For example, a user has $ 20 in a balance field. I want to add $ 1 to make it $ 21. The only way I know how to do this is to use

$balance = $this->Model->find('first', array(
    'conditions' => array('User.id' => $userId),
    'fields' => array('User.balance')
));

$this->Model->save(array(
    'User' => array('id' => $userId, 'balance' => $balance['User']['balance'] + $credit)
));

How can I get all this in one call save?

+5
source share
3 answers

try the following: -

public function edit($id = null) {
        $this->layout = 'admin_layout';
        $this->Model->id = $id;
        if (!$this->Model->exists()) {
            throw new NotFoundException(__('Invalid model'));
        }
        if ($this->request->is('post') || $this->request->is('put')) {
            if ($this->Model->save($this->request->data)) {
                $this->Session->setFlash(__('The model has been saved'));
                $this->redirect(array('action' => 'index'));
            } else {
                $this->Session->setFlash(__('The model could not be saved. Please, try again.'));
            }
        } else {
            $this->request->data = $this->Model->read(null, $id);
        }
        $datd = $this->Model->find('list');
        $this->set('data', $datd);
    }
+1
source

This should do:

$this->User->updateAll(array('User.balance' =>'User.balance + 1'), array('User.id' => $id));
+8
source
$this->Model->saveField('balance','balance+1');

Do the trick!

+3
source

All Articles