public function nearby()
{
$user = auth()->user();
$lat = auth()->user()->latitude;
$lon = auth()->user()->longitude;
$radius = 3; // km => converted to meter
$angle_radius = (float)$radius / ( 111 * cos( (float)$lat ) ); // Every lat|lon degree° is ~ 111Km
$min_lat = (float)$lat - (float)$angle_radius;
$max_lat = (float)$lat + (float)$angle_radius;
$min_lon = (float)$lon - (float)$angle_radius;
$max_lon = (float)$lon + (float)$angle_radius;
$persons = User::where('status', STATUS::ACTIVE)
->where('id', '!=', $user->id)
->whereBetween('latitude', [$min_lat, $max_lat])
->whereBetween('longitude', [$min_lon, $max_lon])
->get();
$persons->each(function($person) {
/* auth user coordinate vs user's coordinates */
$point1 = array('lat' => auth()->user()->latitude, 'long' => auth()->user()->longitude);
$point2 = array('lat' => $person->latitude, 'long' => $person->longitude);
$distance = $person->getDistanceBetweenPoints($point1['lat'], $point1['long'], $point2['lat'], $point2['long']);
$person['distance'] = $distance;
});
return $persons;
}
我正在根据用户的长/纬度在3公里范围内搜索用户 . 我正在将auth long / lat与附近的用户long / lat进行比较 . 它返回带距离的用户集合 .
现在我无法按距离排序 .
如果我添加orderBy('distance','desc')当然会导致错误,因为我的数据库上没有距离列 .
他们是一种对它进行排序和分页的方法 .
2 回答
$persons
变量是一个集合对象,您可以使用此处文档中的集合方法:https://laravel.com/docs/5.6/collections#available-methods您可以使用集合对象的
sortBy
函数 .laravel的分页是在数据库查询级别(https://laravel.com/docs/5.6/pagination),因此您可以使用eloquent
orderBy
方法 .如果你想使这个工作,在一个用户表中放一个
distance
列,但我认为你不希望这样,因为你以编程方式计算getDistanceBetweenPoints
中的距离 .我想到的另一个解决方案是为每个用户的距离创建一个单独的表 .
您必须考虑一种解决方案,它将在数据库查询级别中对距离进行排序 .
希望这能帮助您解决问题:latitude/longitude find nearest latitude/longitude - complex sql or complex calculation
这可能有所帮助 .