多对多查询问题的后续处理

c2e8gylq  于 2021-06-23  发布在  Mysql
关注(0)|答案(2)|浏览(355)

所以,我有一个现有的mysql数据库,我正试图连接到sequelize-in节点,它有一个products表、一个categories表和一个categories\u-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);
});

我得到我的产品,每一个都有一个类别数组,但每个产品只显示一个类别的最大值。我有产品,应该有许多类别,但它只显示第一。
我错过什么了吗?任何帮助都将不胜感激。

hgncfbus

hgncfbus1#

我想你应该用 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);
})
vcudknz3

vcudknz32#

虽然发问者可能已经得到了解决方案,但我遇到了这个复合键表问题,这是代码示例的解决方案。注意“through”关键字。这就解决了你想把你的发现限制在上面提到的某个类别的关联。您的类别id将放在文字表达式中。也适用于芬德尔。

const products = await Product.findAndCountAll({
        include: [Category],
        through: { where: { category_id: `${category_id}` } },
        attributes: [
          'product_id',
          'name',

        ],

        limit: limitPage,
        offset: offsett,
      });

相关问题