如何使用使用者的出生日期来计算使用者的平均年龄 [英] How to calculate the average age of users using their birth dates
本文介绍了如何使用使用者的出生日期来计算使用者的平均年龄的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想使用用户的出生日期来计算他们的平均年龄.我有一个名为 Member
的Model类,其中包括一个用于获取用户年龄的函数.
I want to calculate the average age of users using their birth dates. I have a Model class called Member
, including a function to get the age of the user.
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Carbon\Carbon;
class Member extends Model {
public static function averageAge() {
//What to do here
}
public function age() {
$birthDate = Carbon::parse($this->birthDate);
return $birthDate->diffInYears(Carbon::now());
}
}
推荐答案
Carbon 具有一种计算日期年龄"的方法,因此您可以在模型中执行此操作:>
Carbon has a method to calculate the "age" of a date, so you can do this in your model instead:
class Member extends Model
{
protected $casts = [
'birthDate' => 'date',
];
public function getAgeAttribute()
{
return $this->birthDate->age;
}
}
如果您要计算多个成员的平均年龄,那么我将创建一个类,该类接受一组成员并返回该值:
If you’re wanting to calculate the average age of multiple members, then I’d create a class that takes a collection of members and returns that value:
class AverageAge
{
public static function forMembers(Collection $members)
{
return $members->average(function ($member) {
return $member->age;
});
}
}
然后您可以像这样使用:
Which you can then use like this:
$members = Member::where(...)->get();
$averageAge = AverageAge::forMembers($members);
这篇关于如何使用使用者的出生日期来计算使用者的平均年龄的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文