【问题标题】:Laravel / MySQL Using calculated alias column in where clauseLaravel / MySQL在where子句中使用计算的别名列
【发布时间】:2019-01-23 06:58:44
【问题描述】:

有人可以帮忙看看下面的代码吗?由于列“距离”不存在,即使我将其定义为...

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


【解决方案1】:

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

它只适用于排序、分组和拥有。

你可以使用:

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

我建议对空值使用合并。

编辑

提供的另一个答案也有效。

【讨论】:

    【解决方案2】:

    HAVING 可用于比较别名的值。

    having('distance', '<', $distance);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-03-04
      • 2015-02-14
      • 2011-03-15
      • 1970-01-01
      • 2012-01-12
      相关资源
      最近更新 更多