CakePHP:自动设置模型创建和更新日期
有没有办法配置 CakePHP 模型在保存对象时自动设置时间戳,例如 created_on 和 updated_on?
我正在考虑与 Django 的 DateTimeField 的 auto_now 和 auto_now_add 选项等效的选项。
我听说这在某些框架中是一种有争议的做法,但无论如何我想这样做。
如果您不能做到这一点,人们通常会在 beforeSave() 处理程序中设置时间戳吗?也许是通过检查模型数据是否已包含 id 字段并相应地设置创建数据?
谢谢,如果我错过了文档中的相关部分,我深表歉意。
Is there a way to configure CakePHP models to automatically set timestamps, such as created_on and updated_on, when saving the object?
I'm thinking of an equivalent to Django's DateTimeField's auto_now and auto_now_add options.
I've heard this is a controversial practice in some frameworks, but I want to do it anyway.
If you can't do this, do people normally set the timestamps in the beforeSave() handlers, perhaps by checking if the model data already contains an id field and setting a creation data accordingly?
Thanks, and apologies if I've missed the relevant bit in the docs.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
是的,CakePHP 会自动对
created
和modified
字段执行此操作。在 MySQL 中,这些字段的类型应该是 DATETIME(或 DATE)和 NULLable。
Yes, CakePHP does this automagically for the fields
created
andmodified
.In MySQL, the type for these fields should be DATETIME (or DATE) and NULLable.
如果您将字段命名为
created
和modified
并将它们设置为datetime
类型,Cake 将处理其余的事情。 http://book.cakephp.org/complete/1000/Models #created-and-modified-1015If you name your fields
created
andmodified
and make them of typedatetime
, Cake will handle the rest. http://book.cakephp.org/complete/1000/Models#created-and-modified-1015实际上,使用“now()”更新mysql中的日期时间非常简单。
Actually, use "now()" for updating datetime in mysql is simple and easy.