gpt4 book ai didi

javascript - sequelize 和 postgres 按距点的距离排序

转载 作者:搜寻专家 更新时间:2023-10-31 23:07:37 24 4
gpt4 key购买 nike

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

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
})

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

最佳答案

以下语句将在您的纬度和经度范围内找到Flats,在有效载荷中包含一个名为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。因此,我使用米来测量距离,但您可能需要在代码中将米转换为半径。

关于javascript - sequelize 和 postgres 按距点的距离排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49010851/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com