Billy
Billy

Reputation: 15

Sequelize Many to Many - Updating associations table

I'm building an app using Sequelize with Node.js where I have a Product model and a Category model.

A product can have many Categories, and a category can have many products. And I'd like to update the associations (adding and removing categories of a product) How can I update the association table?

db.Product.find({
  where: {
    id: 1
  }
}).then((res) => {
  //  Updating associations table HERE
})

Upvotes: 0

Views: 443

Answers (1)

Anatoly
Anatoly

Reputation: 22758

Here I'm assuming you have an association definition like this:

Product.belongsToMany(Category,
  { through: ProductCategory, foreignKey: 'productId', otherKey: 'categoryId' })
//  Updating associations table HERE
res.addCategories(categories).then(x => {
// categories added successfully to the product
})

Upvotes: 1

Related Questions