角色和权限之间的多对多关联。协会成功完成
加入表名为RolePermission
我将数据保存在这样的角色
中models.Role.create(role)
.then(function(data){
// here I create RolePermission with role.id and req.body.permission_id
})
我想知道我在RolePermission中手动插入数据还是可用的任何sequelize
或node.js方法?
就像我看到parent.createChild
一样。我如何使用它或最佳实践?
答案 0 :(得分:1)
当我遇到同样的问题时,我发现文档不是很清楚。所以,让我举一个我自己的例子,也许它会帮助你。
//Oportunity hasMany client
//client hasMany oportunity
//join model is ClientOportunity
Oportunity.belongsToMany(Client, {
through: ClientOportunity,
foreignKey: 'oportunity_id',
as: 'client'
});
//create oportunity and add clients
//data is an array with the oportunity fields plus
//an attribute named 'clients' which is an array of clients
//[{id: 1}, {id: 2}] like so
Oportunity.create(data).then(function(created) {
//you have to make a Sequelize instance out of this clients
var clients = data.clients.map(Client.build.bind(Client));
//created is a Sequelize instance of the created Oportunity
//so we use the magic function defined by sequelize to add clients
//if you are trying to add a client that was already related to the oportunity, sequelize is smart enough to avoid repeating it.
//note that if you are updating the clients, you have to pass all the clients all the time. Otherwise you are overwriting.
created.setClient(clients).then(function(result) {});
});
希望您能以此为例来解决您的问题