I want the previous day's total sales from a MySql database.
My code uses Sequelize.literal. I think it is a little bit ugly. Is there any way to query the data without Sequelize.literal
?
I don't want to use mement.js
// My Current Code
const Sequelize = require('sequelize')
const { Op } = require('sequelize')
const getSalesAmount = async () => {
const grand = await CoreOrder.sum('grandTotal', {
where: {
orderState: {
[Op.not]: 'incomplete'
},
createdAt: Sequelize.literal('CURDATE() - INTERVAL 1 DAY')
}
})
}
You need to get yesterday date either in JS code (using datetime libs like moment.js) or by DB (using a datetime function like ADDDATE):
const grand = await CoreOrder.sum('grandTotal', {
where: {
orderState: {
[Op.not]: 'incomplete'
},
createdAt: Sequelize.fn('ADDDATE', Sequelize.fn('CURDATE'), -1)
}
})
If using Sequelize.fn
instead of Sequelize.literal
really helps you then that's it, though I'd personally pass the constant date to Sequelize calculating it in the code to keep Sequelize query as simple as possible.