简体   繁体   English

在 sequelize 中批量创建连接表数据以建立多对多关联

[英]bulkCreate junction table data in sequelize for establishing many-to-many association

I have two models - User and Flat.我有两个模型 - User 和 Flat。 They have a many-to-many association他们有一个多对多的关联

Flat.belongsToMany(User, { through: FlatMember });
User.belongsToMany(Flat, { through: FlatMember });

Now I have an array of objects storing the data of which user is associated to which Flat现在我有一个对象数组存储哪个用户与哪个平面相关联的数据

flatMemberArray = [{userId: 1, flatId: 'A1'}, 
                   {userId: 2, flatId: 'A1'}, 
                   {userId: 2, flatId: 'A2'}];

How do I do a bulkCreate and insert this flatMemberArray into the junction FlatMember Model.我如何做一个 bulkCreate 并将这个 flatMemberArray 插入到连接 FlatMember 模型中。

I went through the documentation and found no help.我浏览了文档并没有找到任何帮助。 There is a single record creation possible with可以使用单个记录创建

userInstance.setFlats(flatIds); //array of flatIds associated to the user instance

But then I would have to run a for loop for each user to do this insertion.但是,我必须为每个用户运行一个 for 循环才能进行此插入。 There surely must be a better way?肯定有更好的方法吗?

FlatMember.bulkCreate([arrayOfDataObjects])

does work.确实有效。 I am just a ridiculous human being who made an error in creating the Data Objects which had the foreign key id assigned as something that did not exist as a Primary Key in the User model.我只是一个荒谬的人,他在创建数据对象时犯了一个错误,该对象的外键 ID 被分配为在用户模型中作为主键不存在的东西。 The catched error message talked about missing parameters, which I misconstrued.捕获的错误消息谈到缺少参数,这是我误解的。 This is corrected now.现在已更正。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM