【问题标题】:How to insert extra values in many-to-many table with Objection.js?如何使用 Objection.js 在多对多表中插入额外的值?
【发布时间】:2018-04-06 17:33:34
【问题描述】:

我有以下表格

foo     foo_bar    bar
---     -------    ---
id      foo_id     id
        bar_id     data
        num
        desc

foo  bar
---  ---
1    (to be inserted)
2

我想将数据插入到bar 中,将插入的条目链接到foo 表上的现有元素,并使用多对多关系表foo_bar

显然我可以这样做:

await Bar.query()
  .allowInsert('[foo]')
  .upsertGraph({ data: 'todo', [{ id: 1 }]}, { relate: true });

我的Bar 模型有

static get relationMappings() {
  return {
    foo: {
      join: {
        extra: ['num', 'desc'],
        from: 'bar.id',
        through: {
          from: 'foo_bar.bar_id',
          to: 'foo_bar.foo_id',
        },
        to: 'foo.id',
      },
      modelClass: Foo,
      relation: Model.ManyToManyRelation,
    },
  };
}

但是如何在foo_barnumdesc 中插入值?如何在该中间表中插入值?

【问题讨论】:

    标签: javascript typescript objection.js


    【解决方案1】:

    来自文档: 额外属性:此处列出的列在获取时会自动连接到相关对象,并在插入时自动写入连接表而不是相关表。

    您在模型中提到了带有 num 和 desc 列的额外属性,因此您可以将它们直接放在 upsertGraph 中,如下所示:

    await Bar.query() .allowInsert('[foo]') .upsertGraph({ data: 'todo', num: 3, desc: 'bla', [{ id: 1 }]}, { relate: true });

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-01-23
      • 1970-01-01
      • 2012-01-08
      • 1970-01-01
      • 2011-07-04
      相关资源
      最近更新 更多