Can I add a condition to CakePHP's update statement?
- by Don Kirkby
Since there doesn't seem to be any support for optimistic locking in CakePHP, I'm taking a stab at building a behaviour that implements it. After a little research into behaviours, I think I could run a query in the beforeSave event to check that the version field hasn't changed.
However, I'd rather implement the check by changing the update statement's WHERE clause from
WHERE id = ?
to
WHERE id = ? and version = ?
This way I don't have to worry about other requests changing the database record between the time I read the version and the time I execute the update. It also means I can do one database call instead of two.
I can see that the DboSource.update() method supports conditions, but Model.save() never passes any conditions to it.
It seems like I have a couple of options:
Do the check in beforeSave() and live with the fact that it's not bulletproof.
Hack my local copy of CakePHP to check for a conditions key in the options array of Model.save() and pass it along to the DboSource.update() method.
Right now, I'm leaning in favour of the second option, but that means I can't share my behaviour with other users unless they apply my hack to their framework.
Have I missed an easier option?