我的user
类hasMany address
类。 address
类具有范围查询功能,可获取区域附近的所有地址:
public static function scopeGetByDistance($query,$lat, $lng, int $max_distance)
{
return $query->selectRaw('id, lat, lng, profileAddress.idMember, ( 3959 * acos( cos( radians( '. $lat.') ) * cos( radians( lat ) ) * cos( radians( lng ) - radians(' . $lng . ') ) + sin( radians(' . $lat .') ) * sin( radians(lat) ) ) ) AS distance')
->having('distance', '<', $max_distance );
}
我想让所有地址为max_distance
到(lat,lng)
点的用户,并希望按照该距离对其进行排序。
如何使用查询生成器来实现?我尝试过:
$users = \App\User::leftJoin('addresses', function($join){
$join->getByDistance(44.81, 20.46, 20);
})
->select(DB::raw('MIN(distance) as closest'))
->groubBy('user.id')
->orderBy('closest')
->get();
但这会导致
方法Illuminate \ Database \ Query \ JoinClause :: getByDistance不存在。
答案 0 :(得分:1)
尝试这样的事情
$users = DB::table('users as u')
->join('address as ad','u.id','=','ad.uset_id');
->select(DB::raw('(6371 * acos(cos(radians('.$lat.')) * cos(radians(lat)) * cos(radians(lng) - radians('.$long.')) + sin(radians('.$lat.')) * sin(radians(lat )))) AS distance'))
->having('distance','<',$max_distance)
->get();
答案 1 :(得分:0)
好吧,我刚刚发现join and relationships are not supported by Laravel
这是我最后所做的:
$users = \App\User::leftJoin('profileAddress','users.id','=','profileAddress.id')
->selectRaw('profileAddress.*, MIN(3959 * acos( cos( radians( '. $lat.') ) * cos( radians( profileAddress.lat ) ) * cos( radians( profileAddress.lng ) - radians(' . $lng . ') ) + sin( radians(' . $lat .') ) * sin( radians(lat) ) ) ) as closest')
->groupBy('users.id')
->having('closest', '<', 20)
->orderBy('closest')
->get();