2017-02-13 59 views
0

角色和權限之間的多對多關聯。協會成功如何在關聯的mdoe中插入數據sequelize.js,節點

做過的角色一樣加入表名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

您可以使用data.setPermission(permissionInstance或permissionInstance陣列) – yBrodsky

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

}); 

希望你可以用這個作爲一個例子來解決你的問題

+0

created.setClient不是函數 –

+0

setClient是一個神奇的函數sequelize創建,在我的情況下,它有這個名字,因爲我有一個與模型客戶端的關係。你將有相應的模型 – yBrodsky