Wednesday, 17 July 2019

Sequelize: Creating a seeder for table entries that need related entries in other tables

(Sorry for broader topic-- this seems to be where most/all Sequelize posts end up, and I am doing this on Node after all...)TL;DR: I'm trying to seed table data that has complex relations with two other tablesI'm trying to set up a project for which the back-end will run on Node, communicating with a database via Sequelize. A fair amount of data needs to be seeded into the database, so I'm trying to do that with the "seeders" concept that sequelize-cli provides. For most of my data, it's been pretty straight-forward. I even bumbled through a case where bulk-insert into one table (manufacturer_locations) required that the new entries have a foreign key to another table (manufacturers).But now I'm trying to seed something more complex. I have a table, paints, which also has a FK ref to manufacturers ("who makes this paint"). That's covered, I've solved that one already. But for each paint that gets inserted, there are one or more entries into a relation table called paints_tags, and one or two entries into a related table product_codes. For both of these, I need the ID attribute of the related paint before I can add the tag mappings or the product codes. When I prototyped this back-end a while back (in a different language), I didn't bulk-insert paints. Instead, I inserted each one at a time and called SELECT last_insert_rowid() immediately after, to get the ID. I then used the ID for all insertions of tag relationships and new product code records.But Sequelize uses a Promise model for all of the insertions and queries. And I'm still wrapping my head around Promises as a concept, but I do know that I can't just execute a query and force it to resolve before moving on to the next step in my code. So I'm trying to determine the best way to seed this data, within the execution model that Node and Sequelize provide.-Randy

Submitted July 17, 2019 at 07:23PM by rjray

No comments:

Post a Comment