Sequelize Insert many of many
What's the correct way to insert a many-to-many relationship when linking in just one shot? I don't want to create objects first and then set links in another step.
Product.belongsToMany(models.Aisle, { through: 'AisleProduct' });
Aisle.belongsToMany(models.Product, { through: 'AisleProduct'});
var product = models.Product
.build({
AisleId:[1,2] // This does NOT work!
});
product.save();
This does not work.
var product = models.Product.build({});
product.setAisles(AisleId:[1,2]);
product.save();
as setAisles
tries to store an object that doesn't have an identifier yet and throws an exception
source to share
First, you need to create Passes. Sequelize does not support creating a linked object during the relative build phase.
Your code should look something like this:
models.Aisle.create({}).then(function(aisle1) {
models.Aisle.create({}).then(function(aisle2) {
models.Product.create({}).then(function(product) {
product.setAisles([aisle1, aisle2]);
});
});
});
You can create your own beforeCreate
hook that can create passes through parameters before saving the Product.
BelongsToMany
the relation adds another table to your database productAisles
that needs to be populated in order to save the relation, so in practice you won't save any queries if you first create Aisles and then add them to your Product.
source to share