javascript - 续集多对多查询问题
问题描述
所以,我有一个现有的 MySQL 数据库,我试图用 Node 中的 Sequelize 连接它,它有一个 products 表、一个 categories 表和一个 categories_products 表。我想做的是退回产品,每个产品都包含它所属的所有类别。这是我所拥有的:
// Declare Product Model
const Product = sequelize.define('products', {
name: Sequelize.STRING,
description: Sequelize.STRING,
single_price: Sequelize.BOOLEAN,
oz_price: Sequelize.FLOAT,
half_price: Sequelize.FLOAT,
quarter_price: Sequelize.FLOAT,
eigth_price: Sequelize.FLOAT,
gram_price: Sequelize.FLOAT,
unit_price: Sequelize.FLOAT
},
{
underscored: true
});
// Declare Category Model
const Category = sequelize.define('categories', {
name: Sequelize.STRING,
parent_id: Sequelize.INTEGER,
picture_file_name: Sequelize.STRING
},
{
underscored: true
});
// Join Table
const ProductCategory = sequelize.define('categories_products', {
product_id: Sequelize.INTEGER,
category_id: Sequelize.INTEGER,
}, {
timestamps: false,
underscored: true
});
// Do this because there is no id column on ProductCategory table
ProductCategory.removeAttribute('id');
Category.hasMany(Category, { as: 'children', foreignKey: 'parent_id' });
ProductCategory.belongsTo(Product);
ProductCategory.belongsTo(Category);
Product.hasMany(ProductCategory);
Category.hasMany(ProductCategory);
使用此设置,我查询如下:
Product.findAll({
include: [{
model: ProductCategory,
include: [ Category ]
}],
where: { active: true },
limit: 10
}).then(prods => {
res.send(prods);
}).catch(err => {
res.status(500).send(err);
});
我拿回了我的产品,每个产品都有一系列类别,但每个产品最多只显示一个类别。我的产品应该有很多类别,但它只显示第一个。
我错过了什么吗?任何帮助将不胜感激。
解决方案
我认为你应该belongsToMany
在这里使用关联。
您可以像这样定义关联
Product.belongsToMany(Category, { through: ProductCategory, foreignKey: 'product_id' });
Category.belongsToMany(Product, { through: ProductCategory, foreignKey: 'category_id' });
查询可以是
Product.findAll({
include: [Category]
}).then((res) => {
console.log(res);
})
推荐阅读
- discord.js - Discord.JS 音乐机器人立即断开连接
- haskell - 来自巨大 CSV 文件的随机样本
- vue.js - 如何在 Vuex 中存储 Vue.js 组件数据?
- python - 如果另外两列中有数据,则在 Pandas 中创建一个为 True 的新列
- regex - 用文本文件中的制表符替换单个空格的命令
- php - 属性路径中给出的“字符串”、“对象”类型的预期参数
- javascript - 我正在尝试使用 javascript 验证多个 HTML 表单输入,并将 css 更改为无效输入,最好的方法是什么?
- java - 修复字符串中的混合编码
- azure - Azure 数据工厂 (ADF) 与 Azure Functions:如何选择?
- python - 大型对象列表上的多处理 Pool.map() 缩放不良:如何在 python 中实现更好的并行缩放?