在Laravel中返回DateTime格式化字段的Unix-Timestamp格式



我有这样的 Message模型:

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(格式。

但是,当获取模型的实例所有日期字段时,我想要转换为 unix-timestamp 格式,然后返回。

我知道可以在每个字段中使用这样的访问器:

public function getCreatedAtAttribute()
{
    dd(strtotime($this->attributes['created_at']));
    return strtotime($this->attributes['created_at']);
}

但是在这种情况下,我必须为每个字段定义一个函数。

,但我希望一种更简单的方式强制模型将日期字段返回为unix-timestamp格式。

protected $casts = [
    'created_at' => 'timestamp',
    'updated_at' => 'timestamp'
];

在模型中,只需添加这些铸件即可获取Unix Timestamp

您可以覆盖:

protected function getDateFormat()
{
 return 'U';
}

为每列使用时间戳属性:

$model->created_at->timestamp

参考:https://laravel.com/docs/4.2/eloquent#timestamps

最新更新