如何使用 pg-promise 助手返回插入查询结果值

问题描述 投票:0回答:1

我正在使用 pgp.helpers.insert 将数据保存到运行良好的 PostgreSQL 中。但是,我需要返回值以在响应中呈现。我正在使用:

this.collection.one(this.collection.$config.pgp.helpers.insert(values, null, 'branch'))

不返回任何数据。

我想要做的是在成功插入后返回分支id,例如:

INSERT into branch (columns) VALUES (values) RETURNING pk_branchID
node.js postgresql pg-promise
1个回答
6
投票

只需将

RETURNING...
子句附加到生成的查询中即可:

const h = this.collection.$config.pgp.helpers;
const query = h.insert(values, null, 'branch') + 'RETURNING pk_branchID';
      
await this.collection.one(query);

如果你想自动生成插入,你必须有一个大对象。命名空间 helpers 在生成多行插入/更新时最有价值,在这种情况下,ColumnSet 用作静态变量:

const h = this.collection.$config.pgp.helpers;
const cs = new h.ColumnSet(['col_a', 'col_b'], {table: 'branch'});
const data = [{col_a: 1, col_b: 2}, ...];

const query = h.insert(data, cs) + 'RETURNING pk_branchID';
      
await this.collection.many(query);

请注意,在这种情况下,我们会执行 .many,因为预计会返回 1 行或更多行/结果。这甚至可以转换为 id-s 数组:

await this.collection.map(query, [], a => a.pk_branchID);

参见:Database.map

© www.soinside.com 2019 - 2024. All rights reserved.