首页 > 解决方案 > 续集多对多查询问题

问题描述

所以,我有一个现有的 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);
});

我拿回了我的产品,每个产品都有一系列类别,但每个产品最多只显示一个类别。我的产品应该有很多类别,但它只显示第一个。

我错过了什么吗?任何帮助将不胜感激。

标签: javascriptmysqlnode.jssequelize.js

解决方案


我认为你应该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);
})

推荐阅读