首页 > 解决方案 > 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检索它时将其转换为碳实例?

标签: laravelphp-carbon

解决方案


这完全取决于$datetime这个函数是什么以及如何传递它。这显然是一个string,而不是一个Carbon实例,但你没有$datetime在你的问题中包含定义,所以我只能推测。

话虽如此,我还没有看到使用外部变量的 mutators,因为它们通常设计为通过以下方式访问您应用它们的类的属性$this

public function getCreatedAtAttribute(){
  return $this->created_at->timezone('Europe/London');
}

我可以看到的唯一警告是尝试使用$model->created_at. 它应该可以处理它,但是如果遇到问题,可能需要getCreatedAtTzAttribute()通过类似的访问。$model->created_at_tz


推荐阅读