Thanks to Finding sum and grouping in sequelize for calling functions as attirubte
I made some modification it include product ref, order and limit
For most refered products (unique sells):
async function getUniqueBestSelling(limit: number) {
const res = await database.model("order_items").findAll({
attributes: [
"productId",
[sequelize.fn("count", sequelize.col("productId")), "totalOrders"],
],
group: ["productId"],
include: [{ model: database.model("products") }],
order: [[sequelize.col("totalOrders"), "DESC"]],
limit: limit,
});
const plainRes = getPlainRes(res);
return plainRes;
}
For total sales (quantity)
async function getBestSelling(limit: number) {
const res = await database.model("order_items").findAll({
attributes: [
"productId",
[sequelize.fn("sum", sequelize.col("quantity")), "totalQuantity"],
],
group: ["productId"],
include: [{ model: database.model("products") }],
order: [[sequelize.col("totalQuantity"), "DESC"]],
limit: limit,
});
const plainRes = getPlainRes(res);
return plainRes;
}