laravel - Laravel Date Mutator 需要解析吗?
问题描述
默认情况下,Eloquent 会将 created_at 和 updated_at 列转换为 Carbon 的实例。当检索 $dates 属性中列出的属性时,它们将自动转换为 Carbon 实例,允许您在属性上使用 Carbon 的任何方法。
我在日期属性中有以下内容 - 我没有包含 created_at 和 updated_at 列,因为这些列默认情况下按照上述转换:
protected $dates = ['deleted_at'];
然后我在模型上有以下访问器:
public function getCreatedAtAttribute($datetime)
{
return $datetime->timezone('Europe/London');
}
但是,上面会引发以下错误:
Call to a member function timezone() on string
如果我将方法更改为以下方法,它会起作用:
public function getCreatedAtAttribute($datetime)
{
return Carbon::parse($datetime)->timezone('Europe/London');
}
问题是为什么我需要解析它,因为它假设在根据文档https://laravel.com/docs/6.x/eloquent-mutators#date-mutators检索它时将其转换为碳实例?
解决方案
这完全取决于$datetime
这个函数是什么以及如何传递它。这显然是一个string
,而不是一个Carbon
实例,但你没有$datetime
在你的问题中包含定义,所以我只能推测。
话虽如此,我还没有看到使用外部变量的 mutators,因为它们通常设计为通过以下方式访问您应用它们的类的属性$this
:
public function getCreatedAtAttribute(){
return $this->created_at->timezone('Europe/London');
}
我可以看到的唯一警告是尝试使用$model->created_at
. 它应该可以处理它,但是如果遇到问题,可能需要getCreatedAtTzAttribute()
通过类似的访问。$model->created_at_tz
推荐阅读
- android - Youtube Data API Activities.list 端点的 home 参数是否有任何替代方法?
- javascript - 来自 readDocument 的文档大小的 CosmosDB 存储过程启发式
- stored-procedures - 使用存储过程但不返回表数据在 EF Core 中获取输出参数值
- c++ - 包括两个不能同时使用的标头
- arrays - TypeError:无法读取反应js中未定义的属性“名称”
- android - Android图形在不同的api上绘制错误的视角
- laravel - 在 Laravel 中动态更改时区
- javascript - 为什么执行函数时useState不是更新状态
- react-native - iOS 键盘生命周期是什么?
- javascript - 我正在用香草 JS 创建一个刽子手游戏,并且偶然发现了这个我无法弄清楚原因的错误