【问题标题】:Sequelize - function on column in a where clauseSequelize - where 子句中的列上的函数
【发布时间】:2023-03-03 05:15:21
【问题描述】:

我有一个带有 GEOMETRY("Point") 类型属性“位置”的餐厅模型。我正在尝试使用 sequelize 编写一个查询,它将为我提供某个半径内的所有餐厅:

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。

编辑:最终这样做:

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

【问题讨论】:

    标签: node.js postgresql sequelize.js


    【解决方案1】:

    如果您必须将 MySQL 函数添加到某些 where 子句列以及其他列及其条件,您可以这样做。

    Model.findAll({
    where: {
    someColumn: {[Sequelize.Op.eq]: "some value"},
    columnWithFunction: Sequelize.where(Sequelize.fn("UPPER", Sequelize.col("columnWithFunction")), "=", "SOME UPPER CASE VALUE")
         }
    ,...
    })
    

    【讨论】:

      【解决方案2】:

      我假设 radius 是用户所在的计算点, xxx 应该是距离

      检查doc,注意最后一个查询:

      Model.findAll({
           where: sequelize.where(sequelize.fn('FUNCTION',
                  sequelize.col('field')), 'value')
      });
      

      【讨论】:

      • 谢谢!!我认为这会奏效。由于我需要创建一些测试数据,因此无法对其进行测试,但生成的查询看起来还不错。
      • @musicformellons 我已经用适合我的解决方案更新了我的原始帖子
      猜你喜欢
      • 2016-07-09
      • 2021-11-25
      • 1970-01-01
      • 1970-01-01
      • 2018-01-08
      • 2018-10-06
      • 2017-07-26
      • 1970-01-01
      • 2018-07-10
      相关资源
      最近更新 更多