Laravel 存取器的平均值

Laravel average value on accessor

我需要计算用户的平均年龄。

这是我的访问代码

public function getAgeAttribute()
{
    if ($this->birthday)
        return Carbon::parse($this->birthday)->age;
    else
        return 'Unknown';
}

如何计算访问者的平均年龄? 感谢您的帮助..

属性 Carbon 对象的年龄不存在。

您可以使用带有实际日期的 diffInYears 来计算年龄

public function getAgeAttribute()
{
    if ($this->birthday)
        return Carbon::now()->diffInYears(Carbon::parse($this->birthday));
    else
        return 'Unknown';
}

在您的模型中,您可以添加受保护的 属性 $dates 以便直接检索 Carbon 对象而不进行解析。

在你的 User.php:

public function getAgeAttribute()
{
  if ($this->birthday)
    return Carbon::parse($this->birthday)->age;
  else
    return 'Unknown';
}

如果你想计算所有用户的平均年龄,把它放在你需要的地方:

User:all()
    ->where('age', '!=', 'Unknown')
    ->avg('age');

这不会包括没有出生日期的用户,因为这没有意义。

如果 birthday 属性在用户 table 中,那么不 select 没有生日的用户会更有效:

User:whereNotNull('birthday')
    ->get()
    ->avg('age');