I have 2 scopes, one that finds the Lat and Long of a zip code, and one that takes the lat and long and returns all the zipcodes in a radius. I would like to create a scope that is
Zipcode::nearby($zipcode, $radius);
and return all the near by zip codes. So basically it looks up the lat and long and then does the lookup. My goal is to do it in 1 query to the sql server if possible.
To lookup the coorindates i am doing
Zipcode::where('zipcode', '12027')->get();
Then to get nearby results
public function scopeNearbyCoordinates($query,$latitude, $longitude, $radius = 10){
$query->select('zipcodes.zipcode')
->selectRaw('( 3959 * acos( cos( radians(?) ) *
cos( radians( Latitude ) )
* cos( radians( Longitude ) - radians(?)
) + sin( radians(?) ) *
sin( radians( Latitude ) ) )
) AS distance', [$latitude, $longitude, $latitude])
->havingRaw("distance < ?", [$radius])
->groupBy('zipcode')
->orderBy('distance');
}
Can this be done in one query?
via brandenwagner