Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 
like image 602
Anonymous Zombie Avatar asked Mar 30 '17 10:03

Anonymous Zombie


1 Answers

The solution which works for me is this:-

// here startDate and endDate are Date objects 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).

like image 156
Akshay Pratap Singh Avatar answered Sep 20 '22 11:09

Akshay Pratap Singh