没有联结表如何获取具有多对多关系的数据

时间:2019-08-31 18:25:36

标签: node.js sequelize.js

我这里有两个桌子。供应商和产品类别。虽然我想使用ProductCategory表从Suppliers表中获取数据,但它也显示联结表数据。我如何摆脱这个问题?

控制器代码

self

型号

exports.getSuppliers = (req, res) => {
    Suppliers.findAll({
        include: [
            { model: ProductCategory, attributes :['categoryName'],}
        ]
    }).then(supplier =>{
        res.send(supplier);
    }).catch();
}

结果

module.exports = (sequelize, DataTypes) => {
  const Suppliers = sequelize.define('Suppliers', {
    sup_Name: DataTypes.STRING,
    email: DataTypes.STRING,
    contact_person: DataTypes.STRING,
    contact_person_phone: DataTypes.STRING
  }, {});
  Suppliers.associate = function(models) {
    // associations can be defined here
    Suppliers.belongsToMany(models.Product_Category, {through: models.Suppliers_has_categories, foreignKey: 'supplier_id'})
  };
  return Suppliers;
};

我只需要ProductCategory表中的此categoryName

1 个答案:

答案 0 :(得分:0)

我可以通过添加through: { attributes: [] }来排除“ Suppliers_has_categories”字段,如下所示。

Suppliers.findAll({
    include: [
        {
            model: ProductCategory,
            attributes :['categoryName'],
            through: { attributes: [] } // <= Add this line.
        }
    ]
})

我在下面的类似问题中找到了这种解决方案。

https://stackoverflow.com/a/45093383/4889634