I am creating an application with Laravel to search businesses by geolocation. I have two models which my eloquent query needs to look at: Businesses and Subscriptions. A business could have many subscriptions (usually only one active at a time), the subscription model contains a end_date
which I would like to include in my results and order them by it (DESC).
I have already built the geolocation search query scope within my Business model:
public function scopeDistance($query,$from_latitude,$from_longitude,$distance)
{
$raw = \DB::raw('ROUND ( ( 3959 * acos( cos( radians('.$from_latitude.') ) * cos( radians( latitude ) ) * cos( radians( longitude ) - radians('.$from_longitude.') ) + sin( radians('.$from_latitude.') ) * sin( radians( latitude ) ) ) ), 1 ) AS distance');
return $query->select('*')->addSelect($raw)->orderBy( 'distance', 'ASC' )->groupBy('distance', 'id')->having('distance', '<=', $distance);
}
I have tried to incorporate this with a left join for related subscriptions:
$businesses = Business::distance($place['lat'], $place['lng'], $request->distance)
->leftJoin('premium_subscriptions', function($join) {
$join->on('businesses.id', '=', 'premium_subscriptions.business_id');
})
but I get the following error:
SQLSTATE[23000]: Integrity constraint violation: 1052 Column 'id' in group statement is ambiguous
What I am trying to achieve is a returned list of businesses within my geolocation parameters but also an retrieve the latest subscription for that business (if any, by newest end_date value) and include subscription.end_date
in my returned results to display them by furthest end_date
in descending order.
I'd appreciate if someone could advise the best method to do this.