gpt4 book ai didi

javascript - 如何在sequelize.js、node中以关联模式插入数据

转载 作者:行者123 更新时间:2023-12-03 05:01:27 26 4
gpt4 key购买 nike

Angular 色和权限之间的多对多关联。关联成功

连接表名称为RolePermission

我以这样的 Angular 色保存数据

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 。我如何使用它或最佳实践?

最佳答案

当我遇到同样的问题时,我发现文档不是很清楚。那么让我给你举一个我自己的例子,也许对你有帮助。

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

});

希望您能以此为例来解决您的问题

关于javascript - 如何在sequelize.js、node中以关联模式插入数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42205876/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com