2

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;    

}
Erubiel
  • 2,934
  • 14
  • 32
Haidar Al
  • 41
  • 1
  • 5

2 Answers2

2

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.

Erubiel
  • 2,934
  • 14
  • 32
2

HAVING can be used to compare the value of an alias.

having('distance', '<', $distance);
Devon Bessemer
  • 34,461
  • 9
  • 69
  • 95