我如何使用 sequelize 搜索带有纬度和经度的数据库 table

how can i search database table with latitude and longitude using sequelize

我有一个商店 table,它有一个列 lat_long,它将每个商店 latitude/longitude 存储为 sequelize 中的几何点。我想根据来自前端请求正文的 latitude/longitude 的接近度来搜索商店。已尝试在 Whosebug 中利用许多与此相关的主题(答案),但了解到查询可以这样写。

const location = sequelize.literal(`ST_GeomFromText('POINT(${lng} ${lat})', 4326)`);

    User.findAll({
      attributes: [[sequelize.fn('ST_Distance_Sphere', sequelize.literal('geolocation'), location),'distance']],
      order: 'distance',
      limit: 10,
      logging: console.log
    })
    .then(function(instance){
      console.log(instance);
    })

已经尝试过了,效果很好,但我面临的挑战是;在这个例子中以及我到目前为止看到的几乎所有示例中,他们都使用了 return 仅距离的属性,但我想 return table 中的所有字段。然后我尝试删除该属性,然后我得到的响应不是基于几何(距离)搜索的,我也尝试使用 where 但出现错误。

下面显示的是我的最新查询,它是 returning 错误,请问我该如何解决这个问题?谢谢。

export const getNearestStoreWithCategory = async (lat, long) => {
  try {
    const location = sequelize.literal(`ST_GeomFromText('POINT(${lat} ${long})')`);
    const distance = sequelize.fn('ST_Distance_Sphere', sequelize.literal('lat_long'), location)
    const storeArr = await Store.findAll({
      order: distance,
      where: sequelize.where(distance),
      limit: 20
    })
    return storeArr
  } catch (error) {
    return error
  }
}

根据 https://sequelize.org/v4/manual/tutorial/querying.html 的文档,我猜您在示例代码中缺少的是包括到要作为数据库响应返回的字段的距离,而不是仅计算距离和返回;

const location = sequelize.literal(`ST_GeomFromText('POINT(${lng} ${lat})', 4326)`);

User.findAll({
    attributes: {
        include: [[sequelize.fn('ST_Distance_Sphere', sequelize.literal('geolocation'), location),'distance']]
    },
    order: 'distance',
    limit: 10,
    logging: console.log
})
    .then(function(instance){
        console.log(instance);
    })

这应该给出这样的查询; SELECT id, OTHER_FIELDS_OF_THIS_TABLE, ST_Distance_Sphere(geolocation) AS distance ...

现在,这是未经测试的代码,但您可以尝试一下,如果有帮助,请发表评论。