Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UPDATE query with CakePHP

I know I can use $this->Model->save() to update a particular record if I pass the id in, but how can I update a single field on that row?

I have a users table with a balance field. I want to update the balance field based on what's already there.

For example, a user has $20 in the 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 that all into one save call?

like image 850
James Dawson Avatar asked Jul 29 '12 02:07

James Dawson


3 Answers

This should do:

$this->User->updateAll(array('User.balance' =>'User.balance + 1'), array('User.id' => $id));
like image 71
tigrang Avatar answered Oct 09 '22 05:10

tigrang


$this->Model->saveField('balance','balance+1');

Should do the trick!

like image 24
David Avatar answered Oct 09 '22 07:10

David


try this:-

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);
    }
like image 28
Abid Hussain Avatar answered Oct 09 '22 07:10

Abid Hussain