简体   繁体   English

使用nodejs的sequelize更新多对多连接表

[英]Updating a many to many join table using sequelize for nodejs

I have a Products table and a Categories table. 我有一个Products表和Categories表。 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. 单个产品可以有许多类别,单个类别可以有许多产品,因此我有一个ProductsCategories表来处理多对多连接。

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). 在下面的示例中,我尝试将我的一个产品(ID为1)与3个不同的类别(ID为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. 我知道下面的代码片段中有些内容已关闭,因为我收到一条丑陋的SQL错误消息,指示我正在尝试将对象插入到ProductsCategories连接表中。 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. 对于这种事情,Sequelize文档非常稀疏。

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. 另外,我正在使用Postgres,不确定这是否重要。

models.Category.findAll returns an array. models.Category.findAll返回一个数组。 By doing setCategories([category]); 通过做setCategories([category]); you are wrapping that array in an array. 您将该数组包装在一个数组中。 Try changing it to setCategories(category); 尝试将其更改为setCategories(category); instead 代替

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]]);
            }
      });  

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM