【问题标题】:How can I limit many-to-many relationships on Sequelize如何限制 Sequelize 上的多对多关系
【发布时间】:2021-01-20 06:11:14
【问题描述】:

我有以下关联:

M:N 关系表

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',
});

当我调用以下方法 CategoryModel.findAll({ include: [ {model: ProductModel, limit: 1} ] }); 时,我会得到如下信息:

“只有 HasMany 关联支持 include.separate”

任何人都知道我该如何处理这个问题并限制包含(多对多)关系? 如果我删除所有预期的限制,我会获得包含相关产品的类别,但我想限制产品。

我会很感激任何帮助,问候。

【问题讨论】:

标签: node.js sequelize.js relationship


【解决方案1】:

Sequelize 仍然不支持对 belongsToMany 关系的限制:

  • 问题#8360已关闭
  • PR #4376 目前已关闭
    questions 答案 1 中提到的针对您的情况的解决方法:
const categories = await CategoryModel.findAll();
const categoriedProductModels = await categories.getProductModels({limit:1});

其他问题是1,2

【讨论】:

    【解决方案2】:
    CategoryModel.findAll({ 
                  include: [ {model: ProductModel} ] , 
                  limit: 1 
          }); 
    

    这会对你有所帮助。

    更多详情请查看此链接https://sequelize.org/v5/manual/models-usage.html

    【讨论】:

    • 这将限制更高级别的模型,即 CategoryModel,而不是包含的模型
    猜你喜欢
    • 2020-10-31
    • 2016-12-15
    • 1970-01-01
    • 2016-03-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-05
    相关资源
    最近更新 更多