数据库
首页 > 数据库> > mysql-Yii2查询未正确引用

mysql-Yii2查询未正确引用

作者:互联网

我一次又一次地遇到这个问题.最好能找到如何正确构建查询的方法,这样我就可以停止使用Yii :: $app-> db-> createCommand()作为解决方法.

我的Yii2查询:

            $users = UserSpatial::find()
            ->select('user_id, harvesine(y(coordinates), x(coordinates), :lat, :lon) as dist, astext(coordinates)')
            ->where('st_within(coordinates, envelope(linestring(point(:rlon1, :rlat1), point(:rlon2, :rlat2))))')
            ->orderBy('st_distance(point(:lon, :lat), coordinates)')
            ->params([
                ':lon' => $geo->lon,
                ':lat' => $geo->lat,
                ':rlon1' => $rlon1,
                ':rlat1' => $rlat1,
                ':rlon2' => $rlon2,
                ':rlat2' => $rlat2
            ])
            ->all();

生成的查询最终在所有错误的地方都带有反引号,而且奇怪的是,并非所有参数都反引号(对不起,但是您需要仔细查找放错了的反引号,因为我不知道如何最好地突出显示不正确的展示位置) :

SELECT \`user_id\`, harvesine(y(coordinates), x(coordinates),      \`32.7699547\`, \`-116.9911288)\` AS \`dist\`, astext(coordinates) 
FROM \`user_spatial\` 
WHERE st_within(coordinates, envelope(linestring(point(-117.07730792871, 32.697490931884), point(-116.90494967129, 32.842418468116)))) 
ORDER BY st_distance(point(-116.9911288, \`32.7699547)\`, \`coordinates)\`

该查询应如下所示,因为我没有在任何字段或值两边加上双角括号:

SELECT \`user_id\`, harvesine(y(coordinates), x(coordinates),      32.7699547, -116.9911288) AS dist, astext(coordinates) 
FROM \`user_spatial\` 
WHERE st_within(coordinates, envelope(linestring(point(-117.07730792871, 32.697490931884), point(-116.90494967129, 32.842418468116)))) 
ORDER BY st_distance(point(-116.9911288, 32.7699547), coordinates)

我可以忍受Yii2在字段名和表名周围添加一些反引号,但是为什么在地球上反引号呢? (仅供参考:$rlon和$rlat值似乎没有被反推,但我认为那是因为它们是数学计算的结果!!!?).

我已经尝试过强制$geo-> lon和$geo-> lat浮动这样的值:

'lon' => (float)$geo->lon;

要么

'lon' => (float)$geo->lon * 1;

但这没有帮助.

解决方法:

尝试对select和orderBy方法使用数组格式,例如docs suggest

Besides column names, you can also select DB expressions. You must use
the array format when selecting a DB expression that contains commas
to avoid incorrect automatic name quoting. For example,

$query->select(["CONCAT(first_name, ' ', last_name) AS full_name",
'email']);

在您的情况下将是这样的:

$users = UserSpatial::find()
->select([
    'user_id', 
    'harvesine(y(coordinates), x(coordinates), :lat, :lon) as dist',
    'astext(coordinates)'
])
->where('st_within(coordinates, envelope(linestring(point(:rlon1, :rlat1), point(:rlon2, :rlat2))))')
->orderBy(['st_distance(point(:lon, :lat)', 'coordinates)'])
->params([
    ':lon' => $geo->lon,
    ':lat' => $geo->lat,
    ':rlon1' => $rlon1,
    ':rlat1' => $rlat1,
    ':rlon2' => $rlon2,
    ':rlat2' => $rlat2
])
->all();

标签:query-builder,yii2,mysql
来源: https://codeday.me/bug/20191119/2034481.html