【问题标题】:Insert with extra field with in many-to-many in Objection.js在 Objection.js 中以多对多方式插入额外字段
【发布时间】:2017-07-12 14:48:13
【问题描述】:

我有以下疑问,我无法在 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 }
    ]
}

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

谢谢!

【问题讨论】:

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


    【解决方案1】:

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

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

    【讨论】:

      【解决方案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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-07-02
        • 1970-01-01
        • 2011-06-27
        • 1970-01-01
        • 1970-01-01
        • 2016-12-17
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多