如何在 laravel 中使用查询生成器计算年龄?
How to calculate age using query builder in laravel?
我已经在 MySQL 数据库中保存了出生日期。
table name : **users**
field name : **dob**
现在我想显示年龄。我的查询是:
$user_info = DB::table('users')->select('(year(curdate())-year(dob)) as age')->get();
我正在使用 Laravel 5.5。
但这是在制造错误。如何在 laravel?
中使用查询生成器计算年龄
您可以使用 selectRaw
,然后像这样使用 mysql 函数
$user_info = DB::table('users')
->selectRaw("TIMESTAMPDIFF(YEAR, DATE(dob), current_date) AS age")
->get();
您可以像这样在模型中定义函数
public function age() {
return $this->dob->diffInYears(\Carbon::now());
}
之后你可以这样称呼它
{{ $user->age() }}}
我建议您在 app/User.php
模型中创建自定义属性。
例如:
在你的User.php
public function getAgeAttribute() {
return $this->dob->diffInYears(\Carbon\Carbon::now());
}
在 controller
and/or view
中,您现在可以通过执行以下操作将此方法作为属性访问:
Auth::user()->age;
这将根据 getAgeAttribute()
在您的用户模型中设置一个属性。
有关更多信息,请查看:https://laravel.com/docs/5.6/eloquent-mutators#accessors-and-mutators
我已经在 MySQL 数据库中保存了出生日期。
table name : **users**
field name : **dob**
现在我想显示年龄。我的查询是:
$user_info = DB::table('users')->select('(year(curdate())-year(dob)) as age')->get();
我正在使用 Laravel 5.5。
但这是在制造错误。如何在 laravel?
中使用查询生成器计算年龄您可以使用 selectRaw
,然后像这样使用 mysql 函数
$user_info = DB::table('users')
->selectRaw("TIMESTAMPDIFF(YEAR, DATE(dob), current_date) AS age")
->get();
您可以像这样在模型中定义函数
public function age() {
return $this->dob->diffInYears(\Carbon::now());
}
之后你可以这样称呼它
{{ $user->age() }}}
我建议您在 app/User.php
模型中创建自定义属性。
例如:
在你的User.php
public function getAgeAttribute() {
return $this->dob->diffInYears(\Carbon\Carbon::now());
}
在 controller
and/or view
中,您现在可以通过执行以下操作将此方法作为属性访问:
Auth::user()->age;
这将根据 getAgeAttribute()
在您的用户模型中设置一个属性。
有关更多信息,请查看:https://laravel.com/docs/5.6/eloquent-mutators#accessors-and-mutators