How can I limit many-to-many relationships on Sequelize

Viewed 1312

I have following associations:

M:N relationship table

ProductCategory.hasMany(Product, { foreignKey: 'productId' });
ProductCategory.hasMany(Category, { foreignKey: 'categoryId', required: true });
  
   Category.belongsToMany(Product, {
      through: {
        model: ProductCategory,
      },
      otherKey: 'productId',
      foreignKey: 'categoryId',
    });


Product.belongsToMany(Category, {
  through: {
    model: ProductCategory,
    unique: false,
  },
  otherKey: 'categoryId',
  foreignKey: 'productId',
});

When I invoke following method CategoryModel.findAll({ include: [ {model: ProductModel, limit: 1} ] }); I get something like this:

"Only HasMany associations support include.separate"

Anyone knows how can I handle this and limit include (many-to-many) relationship? If I remove limit everything works that's expected, I get categories with their associated products, but I want to limit products.

I will appreciate any help, regards.

2 Answers

Sequelize still doesn't support limit on belongsToMany relations:

  • issues #8360 closed
  • PR #4376 closed currently
    Workaround for your case as mentioned in this questions Answer 1:
const categories = await CategoryModel.findAll();
const categoriedProductModels = await categories.getProductModels({limit:1});

Alternative questions are 1,2

Related