SequelizeEagerLoadingError:CatalogMembership与产品无关

时间:2019-04-29 15:44:02

标签: sequelize.js

我有两个模型,产品模型和目录模型,它们通过n:m联接模型CatalogMembership关联。并且我想查询产品模型中属于某些目录的产品。

我尝试了多个版本的“ include”数组,并提供了在这里和其他地方找到的信息。

catalogs.js

module.exports = (sequelize, Sequelize) => {
  const Catalog = sequelize.define('Catalog', {
    ...
  }, {
    ...
  });

  Catalog.associate = (models) => {
    const { Product, CatalogMembership } = models;
    Catalog.Products = Catalog.belongsToMany(Product, {
      through: CatalogMembership,
      foreignKey: 'catalog_id',
      otherKey: 'product_id',
    });
  };

  return Catalog;
};

product.js

module.exports = (sequelize, Sequelize) => {
  const Product = sequelize.define('Product', {
    ...
  }, {
    ...
  });

  Product.associate = (models) => {
    const { Catalog, CatalogMembership } = models;
    Product.Catalogs = Product.belongsToMany(Catalog, {
      through: CatalogMembership,
      foreignKey: 'product_id',
      otherKey: 'catalog_id',
    });
  };

  return Product;
};

catalog_memberships.js

module.exports = (sequelize, Sequelize) => {
  const CatalogMembership = sequelize.define('CatalogMembership', {
    product_id: { type: Sequelize.INTEGER },
    catalog_id: { type: Sequelize.INTEGER },
    ...
  }, {
    ...
  });

  return CatalogMembership;
};

index.js

if (db[modelName].associate) {
  db[modelName].associate(db);
}

misc_helpers.js

catalogIds = [1, 5, 78];

includeArray = [{
  model: CatalogMembership,
  required: true,
  through: { attributes: [] },
  where: { catalog_id: { [Op.in]: catalogIds } },
}];

result = await products.findAll(
  { where: { someAttribute: 'someValue' }, include: includeArray });

我期望在result中获得一些产品,但是当我将这部分包裹在try-catch-block中时,得到的是这个错误:

SequelizeEagerLoadingError: CatalogMembership is not associated to Product

0 个答案:

没有答案