Sequelize where year and months

Viewed 1410

this is my problem, i have two variables, year = 2020 and months = [2,3,5]

i need to get all the appointments that match the year and the months, and my column in the db is a date field (2020-07-06).

this is what i tried, with no success

Appointment.findAll({
        where: {
            date: db.where(db.fn('YEAR', db.col('date')), year),
            [Op.or]: db.where(db.fn('MONTH', db.col('date')), months)
        }
})

i have searched in the documentation how to include the array for the months, and want to get the equivalence to this mysql query

SELECT * FROM appointments WHERE YEAR(date) = 2020 AND ( MONTH(date) = 2 OR MONTH(date) = 3 OR MONTH(date) = 5)
1 Answers

You can just map months to create an array of where for each month.

Appointment.findAll({
  where: {
    date: db.where(db.fn('YEAR', db.col('date')), year),
    [Op.or]: months.map(month => db.where(db.fn('MONTH', db.col('date')), month))
  }
});
Related