Laravel Eloquent使用()位置搜索



我试图返回一个类型为tear的用户列表,这些用户具有关联的教师档案、关联的班级和位置,并且距离邮政编码不到15英里。

它似乎会返回obj值为空的每种类型的每一个用户,如果没有该模型和用户的记录,它会正确地添加到位置的距离,但没有按距离过滤,不知道为什么。

但我想要的只是拥有教师档案(教师模型(和15英里以内位置的用户。

我的型号中的功能

public function searchLocationsByDistance($query, $lat, $lng, $max_distance = 15){
$query->getQuery()->locations = [];
return $query->select('*')
->selectRaw("( 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)
->orderBy('distance');
}

我的控制器中的功能

public function search(Request $request){
$input = $request->all();
//Just google api search this populates fine.
$location =  $this->geolocatePostcode( $input['postal_code'] ); 
$instructors=AppUser::with(['teacher', 'teacher.class','teacher.location' => function ($query) 
use($location) {
$locations = new Location;
$locations->searchLocationsByDistance($query,$location->lat,$location->lng);
}])
//->where('type', '==', 'instructor')
->get();
// var_dump($instructors);
return response()->json($instructors->toArray());
}

有人能告诉我的问题出在哪里吗?或者引导我朝着正确的方向前进。

您的变量在原始查询中是否被正确替换?有几种方法可以做到这一点;

->selectRaw("...query some '$lat' more query...")

->selectRaw("...query some {$lat} more query...")

您也可以用另一种方式替换变量;

->selectRaw("...query some :lat more query...", ['lat' => $lat])

您编写的User查询将返回所有内容,因为该查询没有筛选器。我认为使用Laravel方法whereHas()会对您有所帮助。

尝试一下,但我猜你需要根据需要进行调整,但这应该会给你一个帮助的想法:

$instructors=AppUser::whereHas(['teacher', function($query) use($location){
$query->with(['class', 'location' => function($q) use($location){
$locations = new Location;
$locations->searchLocationsByDistance($q,$location->lat,$location->lng);
}])->where('type', '==', 'instructor');
}])
->get();

此外,在查询中新建Location可能无法按预期工作,而且看起来很复杂。您可能希望首先提取筛选后的教师列表,在内部查询中仅使用$query->with(['class', 'location']);,然后在集合上使用搜索位置方法。测试两种方法,看看什么最有效/效果最好。

最新更新