Could someone please help with the code below. I am getting an error due to the coloumn ‘distance’ not exsisting even though I have defined it as...
public static function getByDistance($lat, $lng, $distance)
{
$result = Auction::join('users', 'auctions.user_id', '=', 'users.id')
->select(DB::raw('users.id', '( 3959 * acos( cos( radians(' . $lat . ') ) * cos( radians( lat ) ) * cos( radians( lng ) - radians(' . $lng . ') ) + sin( radians(' . $lat .') ) * sin( radians(lat) ) ) ) as distance'))
->where ('distance', '<', $distance)
->get();
return $result;
}
MySQL Dropped this kind of comparison to an alias column some versions ago.
It just works for sorting and grouping and having.
You can use:
whereRaw( '(SUBQUERY) < ?', ['distance' => $distance])
I recommend using coalesce for null values.
Edit
The other answer provided is valid too btw.
HAVING can be used to compare the value of an alias.
having('distance', '<', $distance);