【问题标题】:Sequelize How compare year and month of a dateSequelize 如何比较日期的年份和月份
【发布时间】:2021-08-18 19:31:20
【问题描述】:

我目前有这个代码:

Evento.findAll({
    where: db.sequelize.where(db.sequelize.fn('MONTH', db.sequelize.col('start_date')), req.body.month),
    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"
        });
    }
});

但是我也需要咨询当年的事情,不知道怎么做,各种方法都试过了,都没有得到答案。

我想要的 SQL 查询:

SELECT .... FROM ... WHERE MONTH(start_date)=5 AND YEAR(start_date)=2021 ORDER BY ..

请帮帮我啊¡¡¡

【问题讨论】:

  • 本页说明如何在 Sequelize 中使用 ANDORsequelize.org/master/manual/…
  • 顺便说一句,如果您将查询的谓词更改为范围条件而不是检查组件的相等性(即WHERE startDate => '2021-05-01' AND startDate < '2021-06-01'),您的查询可能会运行得更快,因为这样可以更轻松地利用索引。当然,MySQL 的查询引擎可能已经足够聪明,可以做到这一点,但请务必检查您的 EXPLAIN

标签: mysql node.js sequelize.js


【解决方案1】:
Evento.findAll({
    where: {
        [Op.and]: [
            Sequelize.where(Sequelize.fn('MONTH', Sequelize.col('start_date')), req.body.month),
            Sequelize.where(Sequelize.fn('YEAR', 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',
        });
    }
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多