简体   繁体   中英

Using where condition in sequelize for filtering according to distance

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM