Laravel 中的自定义时间戳
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/29207211/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Custom Timestamps in Laravel
提问by Hassan Saqib
I want to keep the time record of changes in certain columns of my table. How can I get and save timestamp values in db? I am trying to do it in following way but getting always 0000-00-00 00:00:00 in col_edited_at column.
我想在我的表的某些列中保留更改的时间记录。如何在数据库中获取和保存时间戳值?我正在尝试按以下方式进行操作,但在 col_edited_at 列中总是 0000-00-00 00:00:00 。
$case->col_edited_at = time();
$case->save();
回答by lukasgeiter
The other answers are correct but I have an idea of a more elegant solution. So you don't have to think about setting the timestamp anymore. Add this to your model and if you change the column it will refresh the col_edited_at
field:
其他答案是正确的,但我有一个更优雅的解决方案的想法。所以你不必再考虑设置时间戳了。将此添加到您的模型中,如果您更改列,它将刷新该col_edited_at
字段:
public static function boot(){
parent::boot();
static::saving(function($model){
if($model->isDirty('col')){
$model->col_edited_at = Carbon::now();
}
});
}
So when the model is getting saved and col
is dirty (meaning it has changed) the timestamp will be set to the current time.
因此,当模型被保存并且col
变脏(意味着它已更改)时,时间戳将设置为当前时间。
Usage:
用法:
$model = MyModel::find(1);
$model->col = 'foo';
$model->save();
回答by Joe
MySQL timestamp fields by default require the format 0000-00-00 00:00:00
. If you're just wanting to store a unix style "seconds since the epoch" timestamp like that returned by time()
use an integer field, or else use:
默认情况下,MySQL 时间戳字段需要格式0000-00-00 00:00:00
. 如果您只想存储一个 unix 样式的“自纪元以来的秒数”时间戳,例如time()
使用整数字段返回的时间戳,或者使用:
$case->col_edited_at = date('Y-m-d H:i:s');
$case->save();
回答by Md. Sahadat Hossain
simply use
简单地使用
date('Y-m-d H:i:s')
instead of time()
date('Y-m-d H:i:s')
代替 time()