【问题标题】:sequelize & postgis sort by distance from pointsequelize 和 postgres 按距点的距离排序
【发布时间】:2018-08-07 05:29:08
【问题描述】:

我在搜索时遇到问题,包括按距某个点的距离排序。这是我的代码和我正在尝试做的事情。感谢您的帮助

const Sequelize = require('sequelize');

var Flat = db.define('flat', {
    id: {
        type: Sequelize.INTEGER,
        autoIncrement: true,
        primaryKey: true
    }
});

var FlatAddress = db.define('flat_address', {
    id: {
        type: Sequelize.INTEGER,
        autoIncrement: true,
        primaryKey: true
    },
    flat_id: {
        type: Sequelize.INTEGER,
        foreignKey:true,
        allowNull:false,
        references: {
            model:'flats',
            key: 'id'
        }
    },
    city: {
        type: Sequelize.STRING(50) //post_town
    },
    location: {
        type: Sequelize.GEOMETRY('POINT')
    }
});

Flat.hasOne(FlatAddress, { as: 'Address', foreignKey: 'flat_id', otherKey: 'id', onDelete: 'cascade' });

FlatAddress.belongsTo(Flat, { foreignKey: 'id', otherKey: 'flat_id', onDelete: 'cascade' });

我想做这样的事情

var POINT = {lat, lng} ?? 
Flats.findAndCountAll({
        where: filter,
        order:  [
                [ { model: FlatAddresses, as: 'Address' },
 '//here should be something like distance from POINT//', 'ACS']
        ],
        include: [
            { model: FlatAddresses, as: 'Address'}
        ],
        offset,
        limit
    })

我没有找到适合我的案例的示例或文档。谢谢

【问题讨论】:

    标签: javascript node.js postgresql sequelize.js postgis


    【解决方案1】:

    以下语句会在你的经纬度范围内找到Flats,在payload中包含一个名为distance的字段,并按distance排序。

    const myDistance = 10000; // e.g. 10 kilometres
    Flats.findAll({
      attributes: {
        include: [
          [
            Sequelize.fn(
              'ST_Distance',
              Sequelize.col('location'),
              Sequelize.fn('ST_MakePoint', longitude, latitude)
            ),
            'distance'
          ]
        ]
      },
      where: Sequelize.where(
        Sequelize.fn(
          'ST_DWithin',
          Sequelize.col('location'),
          Sequelize.fn('ST_MakePoint', longitude, latitude),
          myDistance
        ),
        true
      ),
      order: Sequelize.literal('distance ASC')
    });
    

    请记住:我不知道您使用的是哪个 SRID。因此,我使用米来测量距离,尽管您可能需要在代码中将米转换为半径。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-11-11
      • 1970-01-01
      • 1970-01-01
      • 2015-10-07
      • 2018-02-02
      • 2015-04-27
      相关资源
      最近更新 更多