Laravel / MySQL在where子句中使用计算的别名列

问题描述 投票:1回答:2

有人可以请帮助下面的代码。由于coloumn'距离'不存在,我收到错误,即使我已将其定义为......

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;    

}
php mysql laravel orm eloquent
2个回答
2
投票

MySQL在某些版本之前删除了与别名列的这种比较。

它只适用于排序和分组并具有。

您可以使用:

whereRaw( '(SUBQUERY) < ?', ['distance' => $distance])

我建议使用coalesce作为空值。

编辑

提供的另一个答案是有效的btw。


1
投票

HAVING可用于比较别名的值。

having('distance', '<', $distance);
© www.soinside.com 2019 - 2024. All rights reserved.