我试图在whereHas中使用whereBetween,但我的whereBetween无法正常工作,因为whereHas没有从我的用户模型获取我的转向属性:
这是我的查询
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();
用户模型
<?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
namespace App;
use Illuminate\Database\Eloquent\Model;
class Location extends Model {
protected $table = 'locations';
public function user()
{
return $this->belongsTo('App\User');
}
}
查询中的出生日期字段没有将转换后的值转换为年,而是获得日期格式的值,如表格中的YYYY-MM-DD。
答案 0 :(得分:0)
我找到了解决方案,但没有必要从其他模型访问该属性,只需使用此whereBetween。
$q->whereBetween(DB::raw('TIMESTAMPDIFF(YEAR,users.date_of_birth,CURDATE())'),array(Input::get('age_from'),Input::get('age_to')));