Laravel 5:从日期字段获取年龄范围之间的用户


Laravel 5: Get users between a range of age from date field

当数据库中的出生日期字段为类型日期如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();

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

用户模型

    <?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();
    }
}
我希望你能帮助我。

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

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