Laravel Raw查询不识别别名

发布于 2025-01-20 21:03:29 字数 732 浏览 0 评论 0原文

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

问题:但现在我想过滤别名。为此,我使用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();

问题: 为什么会这样无法识别别名距离?

What i want: I have a model and want to fire a raw query. I use a selectRaw() for this. Inside the selectRaw I pass the select string with an as as alias. When I fire the query I get the desired list including the alias.

Problem: But now I want to filter the alias. For this I use where Raw. I would also like to change the pure order. For this I use whereRaw() and orderRaw(). Unfortunately, I then get an error message:

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

My query:

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

Question: Why does it not recognise the alias Distance?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

浪漫人生路 2025-01-27 21:03:29

有关别名的信息,请参阅 Mysql 文档

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

标准 SQL 不允许在 WHERE 子句中引用列别名。施加此限制是因为当计算 WHERE 子句时,列值可能尚未确定。例如,以下查询是非法的:

您可以使用 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();

它应该有效。

See Mysql Doc about aliases.

It simply says, that you can't use alias in where clauses, simply because it is not evaluated when where runs.

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:

Instead you can use HAVING or eloquent having function.

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

It should work.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文