使用 Node.js Sequelize 查询月份数据

3

我是一名新手,正在学习使用Node Js。在我的Node Js项目中,我正在使用sequelize ORM来连接MySql数据库。

这是我想要编写的按月查询语句:

SELECT * FROM cubbersclosure WHERE MONTH(fromDate) = '04'

这里的fromDate字段类型为date

enter image description here

以下是我的代码:

var fromDate = '2019-04-01'
var fromDateMonth = new Date(fromDate);
var fromMonth = (fromDateMonth.getMonth()+ 1) < 10 ? '0' + (fromDateMonth.getMonth()+1) : (fromDateMonth.getMonth()+1);

CubbersClosure.findAll({
    where:{
        // select query with Month (04)... //fromMonth
    }
}).then(closureData=>{        
    res.send(closureData);
}).catch(error=>{
    res.status(403).send({status: 'error', resCode:200, msg:'Internal Server Error...!', data:error});
});

这里的fromMonth只获取日期中的月份,所以我想编写选择特定月份数据的代码查询语句。
2个回答

5

我不确定,不过你可以尝试这个方法:

where: {
  sequelize.where(sequelize.fn("month", sequelize.col("fromDate")), fromMonth)
}

我遇到了如下错误:D:\my_project\choose_cubby\internal-test\app\controller\cubber\cubbers.controller.js:907 sequelize.where() - Ramesh S
所以将代码更改为以下内容:where: { $and: sequelize.where(sequelize.fn("monthc", sequelize.col("fromDate")), fromMonth) },但仍然显示错误。 - Ramesh S
替换monthc为month怎么样?有个打字错误。 - kkangil
这是错误 FUNCTION choose_cubby.monthc 不存在 - Ramesh S

1

对于那些寻找Postgres的人,这是一种有点hacky的方法来使其工作(请确保进行单元测试):

const results = await models.users.findAll({
   where: this.app.sequelize.fn('EXTRACT(MONTH from "createdAt") =', 3)
});

你还可以更进一步地查询多个属性,像这样:

const results = await models.table.findAll({
   where: {
     [Op.and] : [
        this.app.sequelize.fn('EXTRACT(MONTH from "createdAt") =', 3),
        this.app.sequelize.fn('EXTRACT(day from "createdAt") =', 3),
     ]
   }
});

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接