【问题标题】:Laravel 5: Get users between a range of age from date fieldLaravel 5:从日期字段获取年龄范围内的用户
【发布时间】:2015-05-28 21:37:01
【问题描述】:

当数据库中的出生日期字段是 date 类型(例如 1989-09-20)时,我在选择年龄范围内的用户时遇到问题。

查询

DB::raw("*, ( 
        3959 * acos( 
        cos(radians(?)) 
        * cos(radians(latitude))
        * cos(radians(longitude) - radians(?)) 
        + sin(radians(?)) 
        * sin(radians(latitude)))
    ) AS distance"))
->having('distance', '<', $distance)
->orderBy("distance")
->setBindings([$lat, $lng, $lat])
->whereHas('user', function($q) {
    $q->whereBetween('date_of_birth',array(Input::get('age_from'),Input::get('age_to')))
      ->where('gender',Input::get('gender'))
      ->where('title','LIKE','%'.Input::get('title').'%');
})
->with('user')
->get();

我正在尝试在用户模型中使用 Carbon 将 date_of_birth 属性转换为多年,但由于仍在查询日期格式而不是年数,因此无法正常工作。

用户模型

    <?php namespace App;

use Illuminate\Auth\Authenticatable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Auth\Passwords\CanResetPassword;
use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
use Illuminate\Contracts\Auth\CanResetPassword as CanResetPasswordContract;

class User extends Model implements AuthenticatableContract, CanResetPasswordContract {

    public function getDateOfBirthAttribute()
    {
        $ca = \Carbon\Carbon::parse($this->attributes['date_of_birth']);

        return $ca->diffInYears();
    }

}

我希望你能帮助我。

【问题讨论】:

    标签: php eloquent laravel-5


    【解决方案1】:

    我找到了解决方案,并且正在使用这个 wheteBetween。

    $q->whereBetween(DB::raw('TIMESTAMPDIFF(YEAR,users.date_of_birth,CURDATE())'),array(Input::get('age_from'),Input::get('age_to')));
    

    【讨论】:

      猜你喜欢
      • 2021-05-23
      • 2017-04-09
      • 1970-01-01
      • 2013-10-06
      • 2015-07-24
      • 1970-01-01
      • 2012-04-17
      • 1970-01-01
      • 2023-02-22
      相关资源
      最近更新 更多