Sequelize - where 子句中的列上的函数 [英] Sequelize - function on column in a where clause
问题描述
我有一个餐厅模型,其属性位置"的类型为 GEOMETRY("Point").我正在尝试使用 sequelize 编写一个查询,该查询将为我提供某个半径内的所有餐厅:
I have a Restaurant model with a property 'location' of the type GEOMETRY("Point"). I'm trying to write a query with sequelize that will give me all the restaurants in a certain radius:
models.Restaurant.findAll({
attributes: ["*", [models.sequelize.fn("ST_Distance_Sphere", models.sequelize.fn("ST_MakePoint", latitude, longitude), models.sequelize.col("location")), "distance"]],
where: {
xxx: {
$lte: radius
}
}
}).then(function(dishes) {
res.status(200).json({dishes: dishes})
});
我不知道我应该在 xxx 的位置写什么.我尝试了各种方法,但每次都会出错.在选择查询中,我首先调用一个函数来从用户当前所在的坐标(纬度、经度)创建一个点.然后我使用一个函数来计算到餐厅位置的距离.
顺便说一句,我正在使用 postgres.
I have no clue what I should write where xxx is. I have tried all kinds of things but get an error every time.
In the select query I'm first calling a function to create a point from the coordinates (latitude, longitude) where to user currently is. Then I use a function to calculate the distance to the location of the restaurant.
I'm using postgres btw.
最终这样做:
models.Restaurant.findAll({
attributes: [
'id',
'name',
'addressLine1',
'addressLine2',
'city',
'zipPostalCode',
'location',
'phoneNumber',
'website',
[
models.sequelize.fn(
'ST_Distance_Sphere', models.sequelize.fn('ST_MakePoint', lat, long), models.sequelize.col('location')
),
'distance',
],
],
where: models.sequelize.and(
models.sequelize.where(
models.sequelize.fn(
'ST_Distance_Sphere', models.sequelize.fn('ST_MakePoint', lat, long), models.sequelize.col('location')
), '>', fromRadius),
models.sequelize.where(
models.sequelize.fn(
'ST_Distance_Sphere', models.sequelize.fn('ST_MakePoint', lat, long), models.sequelize.col('location')
), '<=', toRadius),
models.sequelize.where(
models.sequelize.col('Restaurant.is_online'), true
)
),
})
推荐答案
我假设 radius 是用户所在的计算点,xxx 应该是 distance
I'm assuming radius is that calculated point where the user is, xxx should be distance
检查doc,注意最后一个查询:>
Check the doc, notice the last query:
Model.findAll({
where: sequelize.where(sequelize.fn('FUNCTION',
sequelize.col('field')), 'value')
});
这篇关于Sequelize - where 子句中的列上的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!