我有四个表用户、订单、OrderProducts(加入表)、产品,
我想计算订单表中的totalprice列,OrderProducts有数量和productId,产品有价格列,我想计算订单表中的总价格列,
我需要在 OrderProducts 表中为每件商品添加价格列(价格 * 数量)吗?
您不一定需要在 OrderProducts 表中添加价格列。您可以通过在表之间创建 Sequelize 关联并使用 Sequelize 的聚合函数来实现此目的。
Orders.hasMany(OrderProducts);
OrderProducts.belongsTo(Products);
现在,您可以在查询期间根据关联数据动态计算总价,方法是使用 Sequelize 的 SUM 函数将 OrderProducts 中的数量与 Products 中的价格相乘,从而得出每个订单的总价:
const ordersWithTotalPrice = await Orders.findAll({
attributes: [
'id',
[sequelize.fn('SUM', sequelize.literal('`OrderProducts`.`quantity` * `Products`.`price`')), 'totalPrice']
],
include: [
{
model: OrderProducts,
attributes: [],
include: [
{
model: Products,
attributes: []
}
]
}
],
group: ['Orders.id']
});
console.log(ordersWithTotalPrice);
相当于执行以下SQL查询:
SELECT
Orders.id,
SUM(OrderProducts.quantity * Products.price) AS totalPrice
FROM
Orders
JOIN
OrderProducts ON Orders.id = OrderProducts.OrderId
JOIN
Products ON OrderProducts.ProductId = Products.id
GROUP BY
Orders.id;
此方法可确保 Orders 表中的totalPrice 列保持最新状态,而不需要冗余数据存储。