在Objection.js中使用多对多字段插入多对多字段

时间:2017-07-12 14:48:13

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

我有以下疑问,我无法在objection.js文档中找到清楚的内容。 我有以下2个型号:

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 }
    ]
}

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

谢谢!

2 个答案:

答案 0 :(得分:2)

我向项目维护者询问了这个问题,所以我会回答我自己的问题以防其他人感兴趣:

Country
  .query()
  .insertGraph({
    name: 'Finland',
    languages: [{
      // This is the id of the language. You can change "#dbRef" into
      // some other property by overriding `Model.dbRefProp` but you
      // cannot use the model's id column name.
      "#dbRef": 1,
      oficial: true
    }, {
      "#dbRef": 2,
      oficial: false
    }]
  })

来自:https://github.com/Vincit/objection.js/issues/441

答案 1 :(得分:2)

现在你应该能够简单地说:

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
  });