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

How to return insert query result values using pg-promise helpers

我正在使用 pgp.helpers.insert 将数据保存到运行良好的 PostgreSQL 中。但是,我需要 return 值才能在响应中显示。我正在使用:

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

return没有数据。

我想要的是return插入成功后的分支id,如:

INSERT into branch (columns) VALUES (values) RETURNING pk_branchID

只需将 RETURNING... 子句附加到生成的查询:

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

return this.collection.one(query);

如果你想自动生成插入,你必须有一个大对象。命名空间helpers is mostly valued when generating multi-row inserts/updates, in which case a ColumnSet用作静态变量:

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

var query = h.insert(data, cs) + 'RETURNING pk_branchID';

return this.collection.many(query);

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

的数组
return this.collection.map(query, [], a => a.pk_branchID);

参见:Database.map