我有一个我希望以json身份返回的模型。我也希望返回时间戳。问题是时间戳保存为以下格式2013-10-02 09:45:22但我希望它以不同的格式。我仍然想要数据库中的原始格式,但当它作为JSON输出时我想要2013.10.02。我发现你可以覆盖getDateFormat()但它似乎确实改变了db中使用的格式。
我总是可以在返回之前循环遍历数据,但似乎这种代码属于模型。
已更新回答:
这Add a custom attribute to a Laravel / Eloquent model on load?解释了这是如何运作的。
class User extends Eloquent {
protected $appends = array('my_date');
public function getMyDateAttribute()
{
return date('Y.m.d',strtotime($this->attributes['created_at']));
}
}
关键部分是受保护变量$ append,它确保在使用toArray或Json转换对象时包含访问器。
答案 0 :(得分:4)
您可以创建一个额外的访问者,如:
class User extends Eloquent {
protected $appends = array('my_date');
public function setMyDateAttribute($value)
{
return $this->attributes['my_date'] = $value;
}
public function getMyDateAttribute($value)
{
return date('Y-m-d', strtotime($this->attributes['created_at']) );
}
}
然后像User->my_date;