使用 sequelize 中的 where 条件根据距离进行过滤 [英] Using where condition in sequelize for filtering according to distance

查看:75
本文介绍了使用 sequelize 中的 where 条件根据距离进行过滤的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have to filter the posts based on the distance from current location. Have attached the code below for reference,but it does not work (calculating distance works fine though),only where condition for distance doesn't seems to work. Also when I try the distance filter in top where condition, it throws me posts.distance column not found error

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"],
        },
    });

推荐答案

也许如果您将 where 距离条件移出第一个移动 where 内的包含条件.此外,我建议将您的属性移到第一个 where 条件之上.

Maybe if you move your where distance condition out of the include condition inside the first mobile where. Also i suggest moving your attributes on top of the first where condition.

希望这些更改能够解决您的错误或让您找到解决方案.

Hope these changes will fix your error or move you towards the solution.

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"],
    },
});

这篇关于使用 sequelize 中的 where 条件根据距离进行过滤的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆