Laravel 原始查询无法识别别名

Laravel Raw Query does not recognise alias

我想要什么: 我有一个模型,想触发一个原始查询。我为此使用 selectRaw() 。在 selectRaw 中,我将 select 字符串作为别名传递给 as。当我触发查询时,我得到了包含别名的所需列表。

问题: 但是现在想过滤别名。为此我使用 where Raw。我也想改变纯秩序。为此,我使用 whereRaw()orderRaw()。不幸的是,我随后收到一条错误消息:

SQLSTATE[42S22]: Column not found: 1054 Unknown column 'Distance' in...

我的查询:

Model::selectRaw('col1,col2,col3,
            (6368 * SQRT(2*(1-cos(RADIANS(lat))))) AS Distance')
            ->whereRaw('Distance <= 3')
            ->orderByRaw('Distance')
            ->take(20)
            ->get();

问题:为什么不识别别名Distance?

请参阅 Mysql Doc 关于别名。

它只是说,你不能在 where 子句中使用别名,因为 where 运行时它不会被评估。

Standard SQL disallows references to column aliases in a WHERE clause. This restriction is imposed because when the WHERE clause is evaluated, the column value may not yet have been determined. For example, the following query is illegal:

您可以使用 HAVING 或 eloquent having 函数。

Model::selectRaw('
  col1,
  col2,
  col3, 
  (6368 * SQRT(2*(1-cos(RADIANS(lat))))) AS Distance
')
->having('Distance', '<=' '3')
->orderByRaw('Distance')
->take(20)
->get();

应该可以。