我可以在 CakePHP 的更新语句中添加条件吗?
由于 CakePHP 中似乎不支持 乐观锁定,我正在尝试构建一种实现它的行为。经过对行为的一些研究后,我想我可以在 beforeSave 事件中运行查询来检查版本字段是否未更改。
实现检查,
WHERE id = ?
但是,我宁愿通过将更新语句的 WHERE 子句从 更改为 来
WHERE id = ? and version = ?
这样我就不必担心在读取版本和执行更新之间其他请求更改数据库记录。这也意味着我可以进行一次数据库调用,而不是两次。
我可以看到 DboSource.update() 方法支持条件,但 Model.save() 从未向其传递任何条件。
看来我有几个选择:
- 在
beforeSave()
中进行检查并接受它不是防弹的事实。 - 破解我的 CakePHP 本地副本,检查
Model.save()
的options
数组中的conditions
键,并将其传递给 <代码>DboSource.update() 方法。
现在,我倾向于第二种选择,但这意味着我无法与其他用户分享我的行为,除非他们将我的黑客应用到他们的框架中。
我错过了一个更简单的选择吗?
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 theoptions
array ofModel.save()
and pass it along to theDboSource.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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
当使用
save()
更新记录时,Cake 期望存在id
,并且只会更新具有该id
的记录。您要寻找的是
updateAll()
:When using
save()
to update a record, Cake expects anid
to be present and will update only the record with thisid
.What you're looking for is
updateAll()
:我开始破解我的本地 CakePHP 副本。我最近没有查看最新版本的 CakePHP 是否提供任何新选项。
I went with hacking my local copy of CakePHP. I haven't looked recently to see if the latest versions of CakePHP offer any new options.