Updating a table for many of the many using sequelize for nodejs

I have a product table and a category table. One product can have many categories, and one category can have many products, so I have a ProductsCategories table to handle a many-to-many connection.

In the example below, I am trying to associate one of my products (with identifier 1) with 3 different categories (with identifiers 1, 2, and 3). I know that something is disabled in my code snippet below because I get an ugly SQL error message indicating that I am trying to insert an object into the ProductsCategories connection table. I have no idea how to fix the snippet below or if I'm even on the right track here. Sequelize documentation is pretty rare for this kind of thing.

models.Product.find({ where: {id: 1} }).on('success', function(product) { models.Category.findAll({where: {id: [1,2,3]}}).on('success', function(category){ product.setCategories([category]); }); }); 

I am very grateful for the help, thanks. Also, I use Postgres, not sure if this is important.

+1
source share
2 answers

models.Category.findAll returns an array. By executing setCategories([category]); , you wrap this array in an array. Try changing it to setCategories(category); instead

+6
source

I think you are close. I had a similar problem with some of my code. Try searching the categories found, and then add them. I think this can do the trick.

 models.Category.findAll({where: {id: [1,2,3]}}).on('success', function(category){ for(var i=0; i<category.length; i++){ product.setCategories([category[i]]); } }); 
+1
source

Source: https://habr.com/ru/post/1214512/


All Articles