Sequelize查询时如何同时匹配日期字段的年份和月份
修改后完整代码
// 可选择单独引入操作符,也可以直接使用db.Sequelize.Op const { Op } = require('sequelize'); Evento.findAll({ where: { [Op.and]: [ db.sequelize.where(db.sequelize.fn('MONTH', db.sequelize.col('start_date')), req.body.month), // 此处req.body.year可替换为你实际的年份参数,固定值可直接写2021 db.sequelize.where(db.sequelize.fn('YEAR', db.sequelize.col('start_date')), req.body.year) ] }, order: ['start_date'], attributes: ['id', 'description', 'start_date', 'end_date', 'picture', 'status', 'place', 'text'], include: [{ model: TypeEvent }] }).then(events => { if (events) { res.status(200).send({ events }); } else { res.status(400).send({ message: "without events" }); } });
说明
Op.and会将多个查询条件用AND连接,最终生成的SQL完全符合你需要的WHERE MONTH(start_date)=? AND YEAR(start_date)=?效果- 如果你不想单独引入操作符,也可以直接把两个条件放在数组中赋值给
where,Sequelize默认会按AND逻辑处理,写法更简洁:
where: [ db.sequelize.where(db.sequelize.fn('MONTH', db.sequelize.col('start_date')), req.body.month), db.sequelize.where(db.sequelize.fn('YEAR', db.sequelize.col('start_date')), req.body.year) ]
内容的提问来源于stack exchange,提问作者Mauricio Garrido
相关产品推荐
相关产品推荐

