我有一个 MySQL 查询来计算今年客户的订单数量:
SELECT COUNT(order_id) FROM orders where year(order_datetime) = year(curdate()) and customer_id = 51;
我在尝试转换相同的查询以使用sequelize时遇到了一些困难。使用此代码,我为所有用户返回 0:
db.orders.findAll({
where: {
order_id: orderID,
attempt_datetime: {
$like: '%' + 2016 + '%'
}
},
attributes: [[sequelize.fn('COUNT', sequelize.col('order_id')), 'ordersThisYear']]
}).then(function (result) {
console.log('THIS YEARs ORDERS', result);
}, function (e) {
console.log(e);
});
我在 webstorm 中也遇到以下错误:
Deprecation warning: moment construction falls back to js Date. This is discouraged and will be removed in upcoming major release. Please refer to https://github.com/moment/moment/issues /1407 for more info. Arguments: [object Object]
最佳答案
Sequelize 使用 moment 来操作日期。您可能将 attempt_datetime
定义为日期字段,以便将 %2016%
解析为 2016-01-01 00:00:00
日期。您应该使用 $gte/$lt 运算符,而不是 $like 来处理日期范围,并且您可以使用 momentjs 来处理日期范围:
var moment = require('moment');
db.orders.findAll({
where: {
order_id: orderID,
attempt_datetime: {
$gte: moment(2016, 'YYYY').toDate(),
$lt: moment(2017, 'YYYY').toDate()
}
},
attributes: [
[sequelize.fn('COUNT', sequelize.col('order_id')), 'ordersThisYear']
]
})
关于javascript - 使用带有sequelizejs的日期来统计客户今年的订单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35131134/