我需要计算用户的平均年龄。
以下是我的访问代码
public function getAgeAttribute()
{
if ($this->birthday)
return Carbon::parse($this->birthday)->age;
else
return 'Unknown';
}
我怎么能从accessor中计算出平均年龄?
在你的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
属性在用户表中,不选择没有生日日期的用户会更有效率。
User:whereNotNull('birthday')
->get()
->avg('age');
Carbon对象的属性年龄不存在。
你可以使用diffInYears和实际日期来计算年龄。
public function getAgeAttribute()
{
if ($this->birthday)
return Carbon::now()->diffInYears(Carbon::parse($this->birthday));
else
return 'Unknown';
}
在你的模型中,你可以添加受保护的属性$dates,以便重构一个Carbon对象,并且不要解析。