【问题标题】:Using where condition in sequelize for filtering according to distance在sequelize中使用where条件根据距离进行过滤
【发布时间】:2021-02-09 19:08:30
【问题描述】:

我必须根据与当前位置的距离来过滤帖子。附上下面的代码以供参考,但它不起作用(虽然计算距离工作正常),只有在距离条件似乎不起作用的情况下。另外,当我在 top where 条件下尝试距离过滤器时,它会抛出 post.distance column not found 错误

const posts = await Post.findAll({
        where: {
            mobile: {
                [Op.ne]: mobile,
            },
        },
        attributes: 
            include: [
                [
                    db.Sequelize.fn(
                        "ST_Distance",
                        db.Sequelize.col("location"),
                        db.Sequelize.fn(
                            "ST_MakePoint",
                            parsedLocation.lat,
                            parsedLocation.lng
                        )
                    ),
                    "distance",
                ],
            ],
            where: {
                distance: {
                    [Op.between]: [
                     0,100
                    ],
                },
            },
        },
        include: {
            model: UserProfile,
            attributes: ["username"],
        },
    });

【问题讨论】:

  • 你使用什么数据库?
  • 我使用 Postgres 数据库

标签: javascript node.js sequelize.js


【解决方案1】:

也许如果您将 where 距离条件从第一个移动 where 内的包含条件中移出。 我还建议将您的属性移到第一个 where 条件之上。

希望这些更改能够解决您的错误或推动您找到解决方案。

const posts = await Post.findAll({
    attributes: 
        [[
            db.Sequelize.fn(
                "ST_Distance",
                db.Sequelize.col("location"),
                db.Sequelize.fn(
                    "ST_MakePoint",
                    parsedLocation.lat,
                    parsedLocation.lng
                )
            ),
            "distance"
        ]],
    where: {
       [Op.and]: {
            mobile: {
                [Op.ne]: mobile,
            },
            distance: {
                [Op.between]: [
                 0,100
                ],
            }}
    },
    include: {
        model: UserProfile,
        attributes: ["username"],
    },
});

【讨论】:

  • 尝试此方法时出现以下错误。未处理的拒绝 SequelizeDatabaseError:Query.formatError 中不存在列posts.distance
猜你喜欢
  • 2020-05-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-04-27
  • 2020-11-05
  • 2022-08-08
  • 2016-11-13
  • 1970-01-01
相关资源
最近更新 更多