如何在Objection JS中更新ManyToMany关系?

时间:2019-05-28 13:44:14

标签: objection.js

我正在学习Objection JS。我在通过accounts_roles表相关的帐户和角色表上有manyToMany关系。我想知道是否可以通过执行以下操作来更新帐户模型上的帐户角色:

AccountOne.addRoles([roleId])

AccountOne.removeRoles([roleId])

AccountOne.updateRoles([roleId])

AccountOne.deleteRoles([roleId])

我在线搜索并查看了官方的异议文档。到目前为止,我可以使用角色对象“ x”在我的帐户模型上执行GraphInsert,这将创建一个新角色“ x”,并在accounts_roles中正确定义一个关系。但这总是会产生新的作用。我想添加和删除现有帐户和角色之间的关系。任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:0)

您可以使用relateunrelate以多对多关系将两行连接在一起。显然,要使其有效,必须正确设置模型的relationMappings。我也放置了一对示例模型。至关重要的是,将relationMappings的密钥与您在$relatedQuery方法中输入的内容进行匹配,以调用relate / unrelate

示例模型

//Person and Movie Models
const { Model } = require('objection');

class Person extends Model {
  static tableName = 'persons';

  static get relationMappings() {
    return {
      movies: {
        relation: Model.ManyToManyRelation,
        modelClass: Movie,
        join: {
          from: 'persons.id',
          through: {
            from: 'persons_movies.person_id',
            to: 'persons_movies.movie_id'
          },
          to: 'movies.id'
        }
      }
    };
  }
}

class Movie extends Model {
  static tableName = 'movies';

  static get relationMappings() {
    return {
      persons: {
        relation: Model.ManyToManyRelation,
        modelClass: Person,
        join: {
          from: 'movies.id',
          through: {
            from: 'persons_movies.movie_id',
            to: 'persons_movies.person_id'
          },
          to: 'persons.id'
        }
      }
    };
  }
}

相关示例

  

对于多对多关系,请为联接表创建一个联接行。

const person = await Person
  .query()
  .findById(123);

const numRelatedRows = await person
  .$relatedQuery('movies')
  .relate(50);

// movie with ID 50 is now related to person with ID 123
// this happened by creating a new row in the linking table for Movies <--> Person

不相关的示例

  

对于ManyToMany关系,这将从联接表中删除联接行。

const person = await Person
  .query()
  .findById(123)

const numUnrelatedRows = await person
  .$relatedQuery('movies')
  .unrelate()
  .where('id', 50);

// movie with ID 50 is now unrelated to person with ID 123
// this happened by delete an existing row in the linking table for Movies <--> Person