4
I have a table companies
who has a one to one polymorphic relationship with addresses
I have the parameter of latitude
and longitude
and I would like to order the Commissaries to the distance of the smallest to the greatest. The SQL I have works correctly if I search directly in the table Addresses, but need to be returned companies
.
$request['latitude'] = '-21.12633165824461';
$request['longitude'] = '-47.766933831153125';
$sqlDistance = DB::raw('( 111.045 * acos( cos( radians(' . $request['latitude'] . ') )
* cos( radians( addresses.latitude ) )
* cos( radians( addresses.longitude )
- radians(' . $request['longitude'] . ') )
+ sin( radians(' . $request['latitude'] . ') )
* sin( radians( addresses.latitude ) ) ) )');
return $this->company->with(['bonusRule', 'address'])
->whereHas('address', function (Builder $query) use ($sqlDistance) {
return $query->selectRaw("{$sqlDistance} AS distance")
->orderBy('distance');
})->paginate(10);