Laravel中的自定义时间戳 [英] Custom Timestamps in Laravel
问题描述
我想在表的某些列中保存更改的时间记录.如何获取和保存db中的时间戳值?我正在尝试通过以下方式进行操作,但在col_edited_at列中始终注册为00:00:00.
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.
$case->col_edited_at = time();
$case->save();
推荐答案
其他答案是正确的,但是我有一个更优雅的解决方案.因此,您不必再考虑设置时间戳.将此添加到模型中,如果更改列,它将刷新col_edited_at
字段:
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:
public static function boot(){
parent::boot();
static::saving(function($model){
if($model->isDirty('col')){
$model->col_edited_at = Carbon::now();
}
});
}
因此,当保存模型且col
变脏(意味着已更改)时,时间戳记将设置为当前时间.
So when the model is getting saved and col
is dirty (meaning it has changed) the timestamp will be set to the current time.
用法:
$model = MyModel::find(1);
$model->col = 'foo';
$model->save();
这篇关于Laravel中的自定义时间戳的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!