我正在学习Objection JS。我在通过accounts_roles表相关的帐户和角色表上有manyToMany关系。我想知道是否可以通过执行以下操作来更新帐户模型上的帐户角色:
AccountOne.addRoles([roleId])
AccountOne.removeRoles([roleId])
AccountOne.updateRoles([roleId])
AccountOne.deleteRoles([roleId])
我在线搜索并查看了官方的异议文档。到目前为止,我可以使用角色对象“ x”在我的帐户模型上执行GraphInsert,这将创建一个新角色“ x”,并在accounts_roles中正确定义一个关系。但这总是会产生新的作用。我想添加和删除现有帐户和角色之间的关系。任何帮助将不胜感激。
答案 0 :(得分:0)
您可以使用relate和unrelate以多对多关系将两行连接在一起。显然,要使其有效,必须正确设置模型的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