【问题标题】:Updating Multiple Tables using Node Postgres使用 Node Postgres 更新多个表
【发布时间】:2021-12-01 22:56:15
【问题描述】:

我有两张表,一张存储客户订单,另一张存储特定订单的商品。我正在尝试一次更新这两个表,如下所示:

const updateCustOrder = 'UPDATE orders SET customer=$1, due_date=$2 WHERE order_id=$3';
const updateItem = 'UPDATE items SET order_id=$1, quantity=$2, cost=$3 WHERE item_id=$4';

Promise.all([
   pool.query(updateCustOrder, [customer, due_date, order_id]),
   pool.query(updateItem, [order_id, qty, cost, item_id])
]).then(function() {
   response.status(201).send('Successfully Updated');
}).catch(function (e) {
   response.status(500).send('Updated failed');
});

属性order_id 是orders 表中的主键和items 表中的外键。我遇到的问题是 order 表中的值已成功更新,但 items 表中的值未更新。

【问题讨论】:

  • 你不应该把item_id从第一个数组移动到你做updateItem的第二个数组吗?看起来你错过了 id 并得到了WHERE item_id=undefinded
  • @DmitriiZolotuhin 啊是的,对不起,这只是一个错字,那个错误不在我的原始代码中

标签: javascript node.js promise node-postgres


【解决方案1】:

你有没有调查过knex?它对更痛苦的 SQL 任务有很大帮助。不过,这并不能完全回答您的问题。

您可以尝试使用async/await

我承认我对 Node.js 有点生疏。但是,这样的事情应该可以工作:

async function sqlCalls() {
    const updateCustOrder = 'UPDATE orders SET customer=$1, due_date=$2 WHERE order_id=$3';
    const updateItem = 'UPDATE items SET order_id=$1, quantity=$2, cost=$3 WHERE item_id=$4';


    const first = await pool.query(updateCustOrder, [customer, due_date, order_id]);
    const second = await pool.query(updateItem, [order_id, qty, cost, item_id])

    // Use If/Else for error handling
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-12
    • 1970-01-01
    • 2019-07-10
    • 2017-12-08
    • 1970-01-01
    • 2020-08-13
    相关资源
    最近更新 更多