如何用Knex.js实现列相乘求和?排查‘products.price未找到’错误
问题解答
首先明确:Knex.js支持列相乘计算,但不能直接把相乘表达式传给sum()方法,否则会被当成列名解析,这就是你报错的原因。
你的错误出在sum('products.price * order_items.quantity')这一行——Knex会把整个字符串当作一个列名,给它加上引号,数据库自然找不到名为products.price * order_items.quantity的列,所以抛出"column not found"错误。
解决方法是用knex.raw()包裹相乘表达式,让Knex把它当作SQL计算逻辑而非列名:
await knex('order_items') .where('order_items.order_id', orderID) .leftJoin('products', 'order_items.product_id', '=', 'products.id') .sum(knex.raw('products.price * order_items.quantity as total_amount'))
另外,因为用的是leftJoin,如果存在order_items里的product_id在products表中不存在的情况,products.price会是null,相乘结果也会是null,最终求和时这些null会被忽略。如果想把这种情况的金额算成0,可以用coalesce处理:
await knex('order_items') .where('order_items.order_id', orderID) .leftJoin('products', 'order_items.product_id', '=', 'products.id') .sum(knex.raw('coalesce(products.price, 0) * order_items.quantity as total_amount'))
这样就能正确计算所有订单项的金额总和了。
内容的提问来源于stack exchange,提问作者axel_tahmid
相关产品推荐
相关产品推荐

