我正在使用 NodeJS、BookshelfJS 和 ExpressJS 进行项目。 我的数据库是安装了 Postgis 的 Postgres。 我的表“organizations”有一个“lat_lon”几何列。 我想查询特定纬度/经度点的固定半径内的所有组织。 我试过这样的事情:
var organizations = await Organization.query(function (qb) {
qb.where('ST_DWithin(lat_lon, ST_GeomFromText("POINT(45.43 10.99)", 4326), 1000 )')
}).fetchAll()
和更多组合,但它不起作用。 它返回一个错误
UnhandledPromiseRejectionWarning: Unhandled Promise rejection (rejection id: 1): TypeError: The operator "undefined" is not permitted
似乎期望运算符在 where 条件内,但我已经在处理“lat_lon”列。
我该如何解决? 谢谢
whereRaw
是我遇到类似情况时正在寻找的解决方案。
如果我们使用
where
进行以下查询
qb.where('id', 2')
whereRaw
等价于
qb.whereRaw('id = ?', [2])
我相信这大致相当于您的查询
qb.whereRaw('ST_DWithin(lat_lon, ST_GeomFromText("POINT(45.43 10.99)", 4326), 1000 )')
可以参数化为
qb.whereRaw(
'ST_DWithin(lat_lon, ST_GeomFromText("POINT(?, ?)", 4326), ?)',
[45.43, 10.99, 1000]
)
如果经度、纬度或搜索半径发生变化。
你试过使用 knex.raw() 吗?
var organizations = await Organization.query(function (qb) { qb.where(knex.raw('ST_DWithin(lat_lon, ST_GeomFromText("POINT(45.43 10.99)", 4326), 1000 )')) }).fetchAll()
Edit:使用单引号,这样
POINT(45.43 10.99)
就不会被解释为列名
var organizations = await Organization.query(function (qb) {
qb.where(knex.raw("ST_DWithin(lat_lon, ST_GeomFromText('POINT(45.43 10.99)', 4326), 1000 )"))
}).fetchAll()