pg-promise:在事务中的下一个查询中使用一个查询的结果

我是postgres的pg-promise的node.js,试图用2个插入按顺序进行事务。 第一个插入的结果ID应该在事务的下一个插入中使用。

如果任何查询失败,则回滚。 嵌套第二个db.none里面db.none .then()第一个db.one不会回滚第一个查询。 所以在这里使用一个交易。

我坚持在第二次使用第一个查询的结果。 这是我现在拥有的。

 db.tx(function (t) { return t.sequence([ // generated using pgp.helpers.insert for singleData query t.one("INSERT INTO table(a, b) VALUES('a', 'b') RETURNING id"), t.none("INSERT INTO another_table(id, a_id) VALUES(1, <above_id>), (2, <above_id>)") ]); })... 

使用pgp.helpers.insert为多数据查询生成第二个查询。 但是,想要使用以前的查询结果是不可行的。 是不是!

有没有办法从第一个INSERT获得id ie <above_id>

方法序列可以运行无限序列,与您试图实现的目标无关 – 一个标准/琐碎的事务:

 db.tx(t => { return t.one('INSERT INTO table1(a, b) VALUES($1, $2) RETURNING id', [1, 2], x=>+x.id) .then(id => { return t.none('INSERT INTO table2(id, a_id) VALUES($1, $2)', [1, id]); }); }) .then(data => { // success, data = null }) .catch(error => { // error });