【问题标题】:How to calculate age using query builder in laravel?如何使用 laravel 中的查询生成器计算年龄?
【发布时间】:2018-08-02 12:28:06
【问题描述】:

我已经在 MySQL 数据库中保存了出生日期。

table name : **users**
field name : **dob**

现在我想在视图中显示年龄。我的查询是:

$user_info = DB::table('users')->select('(year(curdate())-year(dob)) as age')->get();

我正在使用 Laravel 5.5。

但这会产生错误。如何在 laravel 中使用查询生成器计算年龄?

【问题讨论】:

  • 你遇到了什么错误?

标签: php mysql laravel query-builder laravel-query-builder


【解决方案1】:

你可以使用selectRaw,然后像这样使用mysql函数

$user_info = DB::table('users')
                ->selectRaw("TIMESTAMPDIFF(YEAR, DATE(dob), current_date) AS age")
                ->get();

【讨论】:

    【解决方案2】:

    我建议您在 app/User.php 模型中创建自定义属性。

    例如:

    在你的User.php

    public function getAgeAttribute() {
        return $this->dob->diffInYears(\Carbon\Carbon::now());
    }
    

    controller 和/或view 中,您现在可以通过执行以下操作将此方法作为属性访问:

    Auth::user()->age;
    

    这将根据getAgeAttribute() 在您的用户模型中设置一个属性。

    欲了解更多信息,请查看:https://laravel.com/docs/5.6/eloquent-mutators#accessors-and-mutators

    【讨论】:

      【解决方案3】:

      你可以像这样在你的模型中定义一个函数

      public function age() {
          return $this->dob->diffInYears(\Carbon::now());
      }
      

      之后你可以这样称呼它

      {{ $user->age() }}}
      

      【讨论】:

        猜你喜欢
        • 2022-01-19
        • 1970-01-01
        • 1970-01-01
        • 2020-05-28
        • 1970-01-01
        • 2013-06-29
        • 1970-01-01
        • 2012-03-26
        • 1970-01-01
        相关资源
        最近更新 更多