【问题标题】:Source object access from ColumnSet从 ColumnSet 访问源对象
【发布时间】:2019-06-21 04:52:00
【问题描述】:

在使用 ColumnSet 中列的 initCB 属性导入数据时,我尝试拆分记录集中的子对象。

但是当我对两个不同的目的地名称但一个来源使用两个不同的初始化函数时,我得到了相同的结果。

const cs = new pgp.helpers.ColumnSet([
  'id',
  { name: 'source_id', prop: 'source', init: function(obj) { return obj.value.id; } },
  { name: 'source_name', prop: 'source', init: function(obj) { return obj.value.name; } },
], { table: 'test_table' });

const data = [
  { id: 1, source: { id: 1, name: 'source1' } },
  { id: 2, source: { id: 1, name: 'source1' } },
  { id: 3, source: { id: 2, name: 'source2' } },
];

const insert = pgp.helpers.insert(data, cs);

结果是:

INSERT INTO "test_table"("id","source_id","source_name") VALUES
  (1,'source1','source1'),
  (2,'source1','source1'),
  (3,'source2','source2')

而不是预期:

INSERT INTO "test_table"("id","source_id","source_name") VALUES
  (1,1,'source1'),
  (2,1,'source1'),
  (3,2,'source2')

似乎第二次调用相同源字段的回调函数覆盖了先前在此源字段上调用另一个回调函数的结果。

如何避免这种情况? 或者在导入过程中有另一种拆分子对象的方法?

【问题讨论】:

    标签: node.js pg-promise


    【解决方案1】:

    选项prop 不太适用。它可以将value 重新映射到不同的属性名称,但它不提供直接对象引用。

    改为使用column descriptor 的属性source 来引用源对象。具有讽刺意味的是,您在数据中也将属性称为 source,这意味着您必须在参考中使用两次 source

    const cs = new pgp.helpers.ColumnSet([
        'id',
        {name: 'source_id', init: c => c.source.source.id},
        {name: 'source_name', init: c => c.source.source.name}
    ], {table: 'test_table'});
    

    第一个sourcepg-promise API 支持的,第二个是你的数据列名:)

    另外,根据documentation,API 将sourcethis 设置为相同,因此如果您更喜欢 ES5 函数语法(您的示例看起来更简洁),那么您可以这样做:

    const cs = new pgp.helpers.ColumnSet([
        'id',
        { name: 'source_id', init: function() {return this.source.id;}},
        { name: 'source_name', init: function() {return this.source.name;}},
    ], { table: 'test_table' });
    

    上面我们有this 指向源数据对象。

    【讨论】:

      猜你喜欢
      • 2012-10-30
      • 2013-04-26
      • 1970-01-01
      • 1970-01-01
      • 2020-10-30
      • 2013-01-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多