【问题标题】:pg-promise, format with json-objectpg-promise,用 json-object 格式化
【发布时间】:2017-07-13 12:17:29
【问题描述】:

从 pg-promise 的示例中,可以像下面这样格式化查询,其中 ${this~} 成为对象中的所有键,即“format()”的第二个参数。

// automatically list object properties as sql names:
format('INSERT INTO table(${this~}) VALUES(${one}, ${two})', {
    one: 1,
    two: 2
});
//=> INSERT INTO table("one","two") VALUES(1, 2)

是否也可以在不显式键入所有值的情况下获取对象的所有值?我想像下面那样做(应该和上面的 sn-p 做同样的事情,但不输入所有值):

format('INSERT INTO table(${this~}) VALUES(${this#})', {
    one: 1,
    two: 2
});

【问题讨论】:

    标签: javascript pg-promise


    【解决方案1】:

    是否可以在不显式键入所有值的情况下也获取对象的所有值?

    不,这是不可能的,因为虽然列名需要相同类型的 SQL 名称转义,但值不需要,它们需要模板化,这只能通过显式定义的变量来实现。

    我想像下面那样做......

    为此,您应该使用库的 helpers 方法:

    const cs = new pgp.helpers.ColumnSet(['one', 'two'], {table: 'my-table'});
    const query = pgp.helpers.insert(values, cs);
    

    【讨论】:

      猜你喜欢
      • 2016-12-21
      • 2021-06-15
      • 1970-01-01
      • 2017-10-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多