我正在尝试使用Dexie.js在JavaScript中创建一个简单的库存/销售应用程序。我不确定如何在不编写糟糕的递归代码的情况下返回总销售金额,该代码仅对一种产品的总销售量运行多次查询。
我的架构有点像这样:
clients: "++id, name, phone",
order: "++id, clientId, daate",
order_content: "orderId, productId, qty",
product: "++id, name, mu, mk_cost, sa_cost, prod_cost",
stock: "++id, date, productId, qty, lot"
我将产品类型以及价格和其他详细信息存储在“产品”中。放置订单时,我将clientId存储在Order中,然后使用order_content作为排序的键,使用“ order_content”将项目存储在该位置。
我基本上想对每一项进行总计,并求和。
我尝试在db.product.each()循环中运行以下代码,但似乎让我很复杂。
var product1Total = 0;
function calculateTotal(productId, price){
db.order_content
.where("productID")
.equals(productId)
.each(function(item){
product1Total += (price * qty)
})
}
谢谢!
如果您的目标是在单个查询中获得特定订单的总价,而prod_cost是产品的成本,并且您想要某个订单的总价,则应执行以下操作:
function calculateTotal (orderId) {
return db.order_content
.where('orderId').equals(orderId).toArray()
.then(orderContents => {
return Promise.all(
orderContents.map(oc => db.product.get(oc.productId))
).then (products => {
return orderContents.reduce (
(total, oc, i) => total + oc.qty * producs[i].prod_cost, 0);
});
});
}
或具有异步功能:
async function calculateTotal (orderId) {
let orderContents = await db.order_content
.where('orderId').equals(orderId).toArray();
let products = await Promise.all(orderContents.map(oc =>
db.product.get(oc.productId));
return orderContents.reduce (
(total, oc, i) => total + oc.qty * producs[i].prod_cost, 0);
}
或使用香草ES5 JavaScript:
function calculateTotal (orderId) {
return db.order_content
.where('orderId').equals(orderId).toArray()
.then(function (orderContents) {
return Dexie.Promise.all(
orderContents.map(function (oc) {
return db.product.get(oc.productId);
})
).then (function (products) {
return orderContents.reduce (
function (total, oc, i) {
return total + oc.qty * producs[i].prod_cost;
}, 0);
});
});
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句