Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sequelize Insert Many to Many

Tags:

sequelize.js

What is the right way to insert in a many-to-many relation while setting references all in one shot? I don't want to xreate objects first and then set the references 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 either

var product = models.Product.build({});
product.setAisles(AisleId:[1,2]);
product.save();

as setAisles tries to save the object which does not have an id yet and throws an exception

like image 524
Morteza Shahriari Nia Avatar asked Jul 13 '26 19:07

Morteza Shahriari Nia


1 Answers

You need to create Aisles first. Sequelize doesn't support creating the associated object during the build phase of the relative.

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 the Aisles via the options before you save the Product.

BelongsToMany relation adds another table to your database productAisles, which needs to be populated to save the relation, so practically you will not save any queries if you first build the Aisles and then add them to your Product.

like image 73
drinchev Avatar answered Jul 18 '26 20:07

drinchev



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!