如何更新 Objection JS 中的多对多关系?

DHC*_*DNS 2 objection.js

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

AccountOne.addRoles([roleId])

AccountOne.removeRoles([roleId])

AccountOne.updateRoles([roleId])

AccountOne.deleteRoles([roleId])

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

tec*_*995 5

您可以使用相关不相关以多对多关系将两行连接在一起。显然,要使其正常工作,您必须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'
        }
      }
    };
  }
}
Run Code Online (Sandbox Code Playgroud)

相关示例

在多对多关系的情况下,创建连接表的连接行。

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
Run Code Online (Sandbox Code Playgroud)

不相关的例子

对于 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
Run Code Online (Sandbox Code Playgroud)