使用 sequelize for nodejs 更新多对多连接表 [英] Updating a many to many join table using sequelize for nodejs

查看:31
本文介绍了使用 sequelize for nodejs 更新多对多连接表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 Products 表和一个 Categories 表.一个产品可以有很多类别,一个类别可以有很多产品,因此我有一个 ProductsCategories 表来处理多对多连接.

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.

在下面的示例中,我试图将我的一种产品(ID 为 1)与 3 个不同的类别(ID 分别为 1、2 和 3)相关联.我知道下面的代码片段中有问题,因为我收到一条丑陋的 SQL 错误消息,表明我正在尝试将一个对象插入 ProductsCategories 连接表中.我不知道如何修复下面的代码段,或者我是否在正确的轨道上.Sequelize 文档对于这类事情非常稀少.

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

非常感谢这里的一些帮助,谢谢.另外,我正在使用 Postgres,不确定这是否重要.

I'd really appreciate some help here, thanks. Also, I'm using Postgres, not sure if that matters.

推荐答案

models.Category.findAll 返回一个数组.通过执行 setCategories([category]); 您将该数组包装在一个数组中.尝试将其更改为 setCategories(category); 而不是

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

这篇关于使用 sequelize for nodejs 更新多对多连接表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆