在Laravel中使用时间戳计算两个日期之间的差异 [英] Calculate difference between two dates with timestamps in Laravel
问题描述
我的表中有一个created_at和Updated_at的时间戳记
I have in my table a timestamps with created_at and updated_at
$table->timestamps();
但是我想添加另一列以天为单位来计算created_at和updated_at之间的差异
But I want to add another column that calculates the difference between created_at and updated_at in days
我应该在SQL还是在控制器中做到这一点?
Should I do that in SQL or in my controller?
推荐答案
您可以在Eloquent模型中执行此操作.假设您的模型名称为 User
.您可以通过定义访问器来创建计算字段.
You can do that from within your Eloquent model.
Let's assume your model has the name User
.
You can create a computed field by defining an Accessor.
class User extends Model
{
$dates = [
'updated_at',
'created_at'
];
$appends = ['diffInDays'];
public function getDiffInDaysAttribute()
{
if (!empty($this->created_at) && !empty($this->updated_at)) {
return $this->updated_at->diffInDays($this->created_at);
}
}
}
一些解释
通过将 created_at
和 updated_at
添加到 $ dates
数组,Laravel会自动将日期值转换为
Some explanation
By adding created_at
and updated_at
to the $dates
array, Laravel automatically casts your date values to Carbon.
Now, if you do something like $user->created_at
, you don't get the string, but a Carbon instance of that date. This allows you to make some nice date calculations, like the one above.
通过使用 getDiffInDaysAttribute
函数添加访问器,您可以像普通属性一样通过 $ user-> diffInDays
调用天差,尽管它不在模型.
By adding an Accessor with the getDiffInDaysAttribute
function, you can call the days difference via $user->diffInDays
like a normal attribute, although it is not on the model.
但是,如果您现在要做类似 $ user-> toArray()
的操作,则 diffInDays
属性将不可用.要始终增加检索用户数据的天数差异,可以将字段添加到 $ appends
数组中.这样,当您通过Eloquent检索用户数据时,将始终返回该字段.
But if you would now do something like $user->toArray()
, the diffInDays
attribute will not be available.
To always add the difference in days when you retrieve User data, you can add the field to the $appends
array.
That way, the field will always be returned when you retrieve User data via Eloquent.
这篇关于在Laravel中使用时间戳计算两个日期之间的差异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!