所以,我有一个现有的MySQL数据库,我试图连接到Node中的Sequelize,它有一个产品表,一个类别表和一个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);
});
我收回了我的产品,每个产品都有一系列类别,但每个产品只显示一个类别。我的产品应该有很多类别,但它只显示第一个。
我错过了什么吗?任何帮助将不胜感激。
答案 0 :(得分:1)
我认为你应该在这里使用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);
})
答案 1 :(得分:0)
尽管发问者可能已经找到了解决方案,但是我遇到了这个复合键表问题,这是带有代码示例的解决方案。注意“ through”关键字。这就是解决关联的原因,您希望将发现限制为上面AbhinavD所要求的类别。您的类别ID将在文字表达式中显示。也适用于findAll。
const products = await Product.findAndCountAll({
include: [Category],
through: { where: { category_id: `${category_id}` } },
attributes: [
'product_id',
'name',
],
limit: limitPage,
offset: offsett,
});