Can I add a condition to CakePHP's update statement?
Since there is no optimistic locking support in CakePHP , I take a hit on creating a behavior that implements it. After doing a little research on the behavior, I think I could fire a request on the beforeSave event to check if the version field has changed.
However, I would rather implement the validation by changing the WHERE clause of the update statement from
WHERE id = ?
to
WHERE id = ? and version = ?
That way, I don't have to worry about other queries changing the database record between the time I read the version and the time I do the update. This also means that I can make one database call instead of two.
I can see that the method DboSource.update()
maintains conditions, but Model.save()
never passes any conditions to it.
I seem to have several options:
- Check in
beforeSave()
and live with the fact that it's not bulletproof. - Hack my local copy of CakePHP to check the key
conditions
in the arrayoptions
Model.save()
and pass it to the methodDboSource.update()
.
Right now I'm leaning towards the second option, but that means I can't share my behavior with other users unless they apply my hack to their structure.
Am I missing an easier option?
source to share
When used save()
to update a record, Cake expects to be present id
and will only update the record with that id
.
What are you looking for updateAll()
:
updateAll(array $fields, array $conditions)
Updates many records in one go. The records to be updated are identified by the $ conditions array, and the fields to be updated, along with their values, are identified by the $ fields array.
For example, to validate all bakers who have been members for over a year, an update call might look something like this:
$this_year = date('Y-m-d h:i:s', strtotime('-1 year')); $this->Baker->updateAll( array('Baker.approved' => true), array('Baker.created <=' => "$this_year") );
source to share