gpt4 book ai didi

node.js - 如何使用Sequelize计算列的所有值的总和

转载 作者:行者123 更新时间:2023-12-03 22:43:53 25 4
gpt4 key购买 nike

我需要使用 Sequelize 计算价格列的所有值的总和,并使用 EJS 显示结果
-- 到目前为止,我的 routes/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 的启动对象。

关于node.js - 如何使用Sequelize计算列的所有值的总和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67722695/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com