在Laravel中为日期时间格式化的字段返回unix-timestamp格式 [英] return unix-timestamp format for datetime formatted field in laravel
问题描述
我有一个像这样的 Message
模型:
I have a Message
model like this :
class Message extends Model
{
protected $primaryKey = 'message_id';
protected $dates = ['created_at', 'updated_at', 'receiver_deleted_at', 'sender_deleted_at', 'sender_read_at', 'receiver_read_at'];
}
您会看到有些日期字段以 DATETIME(YYYY-MM-DD HH:MM:SS)格式保存日期.
As you can see there are some date fields that hold dates as DATETIME(YYYY-MM-DD HH:MM:SS) format.
但是我想在获取模型实例时将所有日期字段转换为 unix-timestamp 格式,然后返回.
But I want when get an instance of model all date fields convert to unix-timestamp format and then return.
我知道可以对每个字段使用这样的访问器:
I know that can use accessor like this for every field :
public function getCreatedAtAttribute()
{
dd(strtotime($this->attributes['created_at']));
return strtotime($this->attributes['created_at']);
}
但是在这种情况下,我必须为每个字段定义一个类似于上面的函数.
But in this case I must define a function like above for each field.
但是我想要一种更简单的方法来强制模型以unix-timestamp格式返回日期字段.
But I want an easier way that force model to return date fields as unix-timestamp format.
推荐答案
protected $casts = [
'created_at' => 'timestamp',
'updated_at' => 'timestamp'
];
在模型中,只需添加这些演员表以获得unix时间戳
In model just add these cast to get unix timestamp
这篇关于在Laravel中为日期时间格式化的字段返回unix-timestamp格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!