首页 > 解决方案 > 为什么在此查询表达式中表别名转换为小写

问题描述

本次查询将获取所有降价超过30%的产品:

return $query->where([
    'Products.reduced_price / Products.price <' => 0.7,
]);

此查询导致以下错误:

Column not found: 1054 Unknown column 'products.price' in 'where clause'

为什么表别名转换为小写?此错误似乎取决于您的 mysql 设置。某些设置似乎不区分大小写(例如我的开发机器),其他设置(例如我的生产服务器)区分大小写;)

不幸的是,在这种情况下不可能省略表别名“Products”,因为有一个连接表也有一个名为“price”的列。省略别名会导致此错误:Column 'price' in where clause is ambiguous

标签: cakephpcakephp-3.0

解决方案


原因是类的_parseCondition方法QueryExpression。它将假定第一个空格之后的所有内容都是运算符并strtolower在其上使用,从而使别名小写。

这可以通过从表达式中删除所有空格来轻松缓解,如下所示:

return $query->where([
    'Products.reduced_price/Products.price <' => 0.7,
]);

推荐阅读