Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Update a row +1 in CakePHP

Tags:

cakephp

I am trying to update a row in the database but haven't found a way to do this in the CakePHP way (unless I query the row to retrieve and update).

UPDATE mytable (field) VALUES (field+1) WHERE id = 1

In CodeIgniter, it would have been as simple as:

$this->db->set('field', 'field+1', FALSE);
$this->db->where('id', 1);
$this->db->update('mytable');

How do I do this without querying the row first, retrieve the value, then updating the row with the information I got?

like image 863
Teej Avatar asked Dec 12 '22 16:12

Teej


1 Answers

I don't think CakePHP has a similar method for doing this in a normal save() on a single row.

But the updateAll() method, which updates multiple rows, does support SQL snippets like so:

$this->Widget->updateAll(
    array('Widget.numberfield' => 'Widget.numberfield + 1'),
    array('Widget.id' => 1)
);

The first param is an array of fields/values to be updated, and the second param are the conditions for which rows to update.

Apart from that I think the only thing is to use:

$this->Widget->query('YOUR SQL QUERY HERE');

Which lets you query with raw SQL. [EDIT: but this is not recommended as it bypasses the ORM.]

like image 169
Jamie Avatar answered Jan 11 '23 02:01

Jamie