Thursday 20 February 2020

[Sequelize/Postgres] Is there an option to add a key value pair (foreign key) to each object in an array when using sequelize.bulkCreate() ?

I have potentially hundreds of rows to insert via an array of objects and I need to pass in a foreign key on save but since this array is being saved within a transaction with constraints deferred I can't just go get the ID so I need it to pass it in on save (or in a way that will work within this context).Is this possible with Sequelize or will I be forced to be a programmer like they pay to be and write this myself? My problem is when i create these objects I have zero context of the parent row's primary id so I can't reference it until this array objects comes back from the module and is sent to the DB create controller where I save everything to postgres.// Parent method gets data from controller parentMethod(data) { sequelizeTransactionWrapper(transaction) { // each constraint is deferred aka the foreign keys so it won't break during this process since they all get created at the same time childMethod1({ primaryId: 123, key: data.something }, { transaction }); childMethod2({ foreignKey: childMethod1.primaryId, key: data.something }, { transaction }); childMethod3({ foreignKey: childMethod1.primaryId, primaryID: 54321, key: data.something, key: data.something }, { transaction }); childMethod4({ arrayOfObjects: [ { foreignKey: how do I add childMethod3's ID here after the objects are already created? ...more data }, { foreignKey: how do I add childMethod3's ID here after the objects are already created? ...more data } ] }, { transaction }); } } Is my best solution here to just loop the array and assign the foreignKey or is there a sequelize way to do this automatically?Sorry if it's not clear, please let me know if you need clarification.Thank you!

Submitted February 20, 2020 at 09:54PM by nullol

No comments:

Post a Comment