javascript - 在 Objection.js 中以多对多方式插入额外字段

标签 javascript node.js typescript knex.js objection.js

我有以下疑问,我无法在 objection.js 文档中清楚地找到。 我有以下两个模型:

export class Language extends BaseId {
    name: string;

    static tableName = 'Languages';

    static jsonSchema = {
        type: 'object',

        required: ['name'],

        properties: {
            name: { type: 'string', minLength: 1, maxLength: 80 }
        }
    };
}

export class Country extends BaseId {
    name: string;
    languages: Language[];

    static tableName = 'Countries';

    static jsonSchema = {
        type: 'object',

        required: ['name'],

        properties: {
           name: { type: 'string', minLength: 1, maxLength: 120 }
        }
    };

    static relationMappings: RelationMappings = {
         languages: {
              relation: Model.ManyToManyRelation,
              modelClass: Language,
              join: {
                  from: 'Countries.id',
                  through: {
                      from: 'CountriesLanguages.country_id',
                      to: 'CountriesLanguages.language_id',
                      extra: ['oficial']
                  },
                  to: 'Languages.id'
              }
          }
     };
}

我想插入一个新的国家,例如:

{
    name: "Country Name",
    languages: [
       { id: 1, official: true },
       { id: 2, official: true },
       { id: 3, official: false }
    ]
}

如您所见,我不想创建新语言,我只想添加具有额外属性的引用。我只是想建立与国家的关系。 这样插入的正确方法是什么?我找不到文档,只是找到了一种创建语言的方法。

谢谢!

最佳答案

现在你应该可以简单地说:

Country.query()
  .insertGraph({
    name: "Country Name",
    languages: [
      { id: 1, official: true },
      { id: 2, official: true },
      { id: 3, official: false }
    ]
  }, {
    // This tells `insertGraph` to not insert new languages.
    relate: true
  });

关于javascript - 在 Objection.js 中以多对多方式插入额外字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45060991/

相关文章:

javascript - 如何在 SVG <line> 元素上使用箭头标记?

javascript - Angular:从标签中应用 ngif

php - 如何从 AJAX 请求返回结果

javascript - 将来自对 REST API 的重复请求的最终 json 写入文件

node.js - 运行 forEach 后返回变量

javascript - 只需稍加调整即可创建从一个对象到另一个对象的 JSON 对象

html - Angular-是否可以在子组件中使用内容投影?

javascript - Vue.js 转换 : animate height while using slide out animation

javascript - 如何在nodeJS中使用phantom包设置自定义页眉和页脚内容?

javascript - 如何在我的 React Typescript 计数器中使用类型接口(interface)来支持钻取?