Can I add a condition to CakePHP's update statement?

Posted by Don Kirkby on Stack Overflow See other posts from Stack Overflow or by Don Kirkby
Published on 2009-09-25T23:26:59Z Indexed on 2010/04/08 5:03 UTC
Read the original article Hit count: 316

Filed under:
|
|

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:

  1. Do the check in beforeSave() and live with the fact that it's not bulletproof.
  2. 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?

© Stack Overflow or respective owner

Related posts about cakephp

Related posts about optimistic-locking