【问题标题】:How to return insert query result values using pg-promise helpers如何使用 pg-promise 帮助器返回插入查询结果值
【发布时间】:2017-06-16 18:47:00
【问题描述】:

我正在使用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】:

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

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

    如果你想自动生成插入,你必须有一个大对象。命名空间 helpers 在生成多行插入/更新时最受重视,在这种情况下,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 行或更多行/结果。这甚至可以转化为一个 id-s 数组:

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

    见:Database.map

    【讨论】:

    • 谢谢。最初,我将 SQL 放在一个文件中,但我想使用这种方式来满足请求中可能缺少的可能为 null 的列值。
    猜你喜欢
    • 2018-10-14
    • 2019-04-16
    • 2021-08-14
    • 1970-01-01
    • 1970-01-01
    • 2017-07-22
    • 1970-01-01
    • 2017-10-14
    • 1970-01-01
    相关资源
    最近更新 更多