Updating a many to many join table using sequelize for nodejs

断了今生、忘了曾经 提交于 2019-12-10 17:52:16

问题


I have a Products table and a Categories table. A single Product can have many Categories and a single Category can have many Products, therefore I have a ProductsCategories table to handle the many-to-many join.

In the example below, I'm trying to associate one of my products (that has an ID of 1) with 3 different categories (that have IDs of 1, 2, & 3). I know something is off in my code snippet below because I'm getting an ugly SQL error message indicating that I'm trying to insert an object into the ProductsCategories join table. I have no idea how to fix the snippet below or if I'm even on the right track here. The Sequelize documentation is pretty sparse 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'd really appreciate some help here, thanks. Also, I'm using Postgres, not sure if that matters.


回答1:


models.Category.findAll returns an array. By doing setCategories([category]); you are wrapping that array in an array. Try changing it to setCategories(category); instead




回答2:


I think you are close. I had a similar issue with some of my code. Try iterating over your found categories and then add them. I think this might 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]]);
            }
      });  


来源:https://stackoverflow.com/questions/29247408/updating-a-many-to-many-join-table-using-sequelize-for-nodejs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!