[英]Sequelize Many to Many Query Issue
因此,我有一個現有的MySQL數據庫,試圖與Node中的Sequelize連接,該數據庫具有一個products表,一個category表和一個category_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);
})
盡管發問者可能已經找到了解決方案,但我遇到了這個復合密鑰表問題,這是帶有代碼示例的解決方案。 注意“ 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,
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.