强制演绎模型输出所有时间戳 [英] Force Eloquent Models to output all timestamps as long
问题描述
$ 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屋!