如何使用Sequelize计算列的所有值的总和

问题描述

我需要使用 Sequelize 计算 price 列的所有值的总和,并使用 EJS 显示结果

-- 到目前为止我的路由/admin.js 代码

const express = require("express");
const Sequelize = require("sequelize");

var Op = Sequelize.Op;

// Load model
var orderModel = require("../models").Order;

const router = express.Router();

router.get("/admin",async function (req,res,next) {

    var pending_orders = await orderModel.count({
        where: {
            status: {
                [Op.eq]: 'p'
            }
        }
    });
    var completed_orders = await orderModel.count({
        where: {
            status: {
                [Op.eq]: 'c'
            }
        }
    });
    var total_orders = await orderModel.count();

    var total_price = await orderModel.findAll({
        // I need to calculate the sum from the all 
        // the values of the Price Colmun
    });

    res.render("admin/dashboard",{
        ordersP: pending_orders,ordersC: completed_orders,ordersT: total_orders,priceT: total_price // Total price should return to here
    });

});
module.exports = router;

-- 总收入 (priceT) 应与 EJS 一起显示在此处

<div>
    <h3> <%= priceT %> </h3>
    <p>Total Income</p>
</div>

orders table screenshot

解决方法

您可以通过两种方式来处理这个主题。

使用原始 SQL 查询

const {sequelize} = require('../models') //Directory to models
const {QueryTypes} = require('sequelize');
const total_price = await sequelize.query('Select SUM(price) From Orders',{type:QueryTypes.SELECT})

在 Sequelize 中使用聚合函数

const {sequelize} = require('../models') //Directory to models - This is the instance 
const Sequelize = require('sequelize') // This the classed sequelize
const total_price = await orderModel.findAll({
   attributes: [
      [sequelize.fn('sum',sequelize.col('price')),'total_price']
    ]
})
在使用上述命令时,除了使用类(导入简单的 cased sequelize )之外,请确保使用 sequelize 的启动对象。