强制演绎模型输出所有时间戳 [英] Force Eloquent Models to output all timestamps as long

查看:136
本文介绍了强制演绎模型输出所有时间戳的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用有说服力的模特在后台工作。为了设置默认的输出日期方式,我正在寻找一种方法来告诉演绎模型将其日期属性输出为长(unix-timestamp)。

  $ user = User:find(id); 
echo $ user-> toJson();

//当前输出

  {
id:1,
username:root,
created_at:2016-12-25 18:23:34 ,
updated_at:2016-12-25 18:23:34
}

//所需的输出

  {
id:1,
username:root,
created_at:1482690214,
updated_at:1482690214
}

有没有干净的方法来覆盖输出的toJson()或任何其他方式来实现这一点?



编辑



你有什么事情要重写魔术__get()吗?或者,在调用toJson时,还可以使用另一种方法访问该属性?

解决方案

设置所需格式 to $ dateFormat 变量

  protected $ dateFormat ='U'; 




默认情况下,时间戳格式为 Ymd H:我:■。如果您需要自定义时间戳格式,请在模型上设置 $ dateFormat 属性。此属性确定日期属性如何存储在数据库中,以及当模型序列化到数组或JSON时的格式。


https://laravel.com/docs/5.3/eloquent-mutators#date- mutators


I'm working on a backend using Eloquent Models. In order to set a default way to output dates, I'm looking for a way to tell the Eloquent Model to output its date attributes as a long (unix-timestamp).

$user = User:find(id);
echo $user->toJson();

// the current output

{
   "id":1,
   "username":"root",
   "created_at":"2016-12-25 18:23:34",
   "updated_at":"2016-12-25 18:23:34"
}

// the desired output

{
   "id":1,
   "username":"root",
   "created_at":1482690214,
   "updated_at":1482690214
}

Is there a clean way to override the outputing toJson() or any other way to achieve this?

Edit

Do you thing that it's a good idea to override the magic __get()? Or does Eloquent use another way to access the attribute when calling toJson?

解决方案

Set desired format to $dateFormat variable:

protected $dateFormat = 'U';

By default, timestamps are formatted as Y-m-d H:i:s. If you need to customize the timestamp format, set the $dateFormat property on your model. This property determines how date attributes are stored in the database, as well as their format when the model is serialized to an array or JSON

https://laravel.com/docs/5.3/eloquent-mutators#date-mutators

这篇关于强制演绎模型输出所有时间戳的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆