使用 nodejs 的 sequelize 更新多对多连接表 [英] Updating a many to many join table using 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
这篇关于使用 nodejs 的 sequelize 更新多对多连接表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!