开发者

CakePHP: auto-set model create and update dates

开发者 https://www.devze.com 2023-01-30 10:24 出处:网络
Is there a way to configure CakePHP models to automatically set timestamps, such as created_on and updated_on, when saving the object?

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.

开发者_StackOverflow社区

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.


Yes, CakePHP does this automagically for the fields created and modified.

In MySQL, the type for these fields should be DATETIME (or DATE) and NULLable.


If you name your fields created and modified and make them of type datetime, Cake will handle the rest. http://book.cakephp.org/complete/1000/Models#created-and-modified-1015


Actually, use "now()" for updating datetime in mysql is simple and easy.

$updateField = array('last_login'=>'now()');
0

精彩评论

暂无评论...
验证码 换一张
取 消