Sequelize Query to find all records that falls in between date range

 ̄綄美尐妖づ 提交于 2020-08-01 05:41:17

问题


I have a model with columns:

from: { type: Sequelize.DATE }
to: { type: Sequelize.DATE }

I want to query all records whose either from OR to falls in between the date ranges : [startDate, endDate]

Tried Something Like:

const where = {
    $or: [{
        from: {
            $lte: startDate,
            $gte: endDate,
        },
        to: {
            $lte: startDate,
            $gte: endDate,
        },
    }],
};

Something Like:

SELECT * from MyTable WHERE (startDate <= from <= endDate) OR (startDate <= to <= endDate

回答1:


The solution which works for me is this:-

# here startDate and endDate are Javascript Date object
const where = {
    from: {
        $between: [startDate, endDate]
    }
};

For reference to know more about operators:- http://docs.sequelizejs.com/en/latest/docs/querying/#operators

Note: In MYSQL between comparison operator is inclusive, which means it is equivalent to the expression (startDate <= from AND from <= endDate).




回答2:


Try this condition what I think you are asking will do so.

For New Version Of Sequelize:

const where = {
    [Op.or]: [{
        from: {
            [Op.between]: [startDate, endDate]
        }
    }, {
        to: {
            [Op.between]: [startDate, endDate]
        }
    }]
};

OR as your code structure:

const where = {
    $or: [{
        from: {
            $between: [startDate, endDate]
        }
    }, {
        to: {
            $between: [startDate, endDate]
        }
    }]
};

For more info you can follow this Sequelize official documents



来源:https://stackoverflow.com/questions/43115151/sequelize-query-to-find-all-records-that-falls-in-between-date-range

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!