node.js - 如何限制 Sequelize 上的多对多关系

标签 node.js sequelize.js relationship

我有以下关联:

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',
});
当我调用以下方法 CategoryModel.findAll({ include: [ {model: ProductModel, limit: 1} ] }); 时,我得到如下信息:
“只有 HasMany 关联支持 include.separate”
任何人都知道我该如何处理并限制包含(多对多)关系?
如果我删除限制,一切正常,我会得到相关产品的类别,但我想限制产品。
我将不胜感激任何帮助,问候。

最佳答案

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

  • 问题 #8360 关闭
  • PR #4376 目前已关闭
    如本 questions 答案 1 中所述,针对您的情况的解决方法:
  • const categories = await CategoryModel.findAll();
    const categoriedProductModels = await categories.getProductModels({limit:1});
    
    
    替代问题是 1 , 2

    关于node.js - 如何限制 Sequelize 上的多对多关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65803974/

    相关文章:

    javascript - Firebase API 用于将 Twig 从一个集合移动到另一个集合

    node.js - 在node.js Express网站中应用jade模板

    node.js - NodeJS 服务器上的 ENOTFOUND 到带有 Docker 的 Redis

    javascript - 为涉及 DataTypes.JSON 的 Sequelize 创建种子文件时出错

    sql-server - 如何将对象数组插入映射表 - Sequelize

    types - Cypher 查询返回 Neo4j 图中每种类型的一个关系

    database - CodeIgniter 中的一对多数据库关系

    javascript - 对列表的所有元素使用函数并等待它们的 promise

    sequelize.js - Sequelize QueryGenerator 和范围

    Laravel/Eloquent 模型关系查看器