【问题标题】:Sequelize - How do I "select" instances of a model if a relation exists to another modelSequelize - 如果与另一个模型存在关系,我如何“选择”模型的实例
【发布时间】:2026-01-20 22:15:02
【问题描述】:

我在 Node.JS 应用程序中使用 PostgreSQL,并且我使用 SequelizeJS 作为 ORM。我有以下查询:

假设我有两个模型:

  • User(name,email)
  • Category(name,createdBy)

Category.createdBy 是引用 User.id 的外键 这两个表是多对多的关系:

Category.belongsToMany(models.User, {through: 'UserCategory'});
User.belongsToMany(models.Category, {through: 'UserCategory'});

如果类别与用户相关联,则 UserCategory 表中将存在映射。否则不会。

如何“选择”可以找到所有类别的实例,这些类别要么由用户 X 创建,要么与用户 X 相关联,即(categories associated to user X) + (categories created by user X)

【问题讨论】:

    标签: node.js postgresql sequelize.js


    【解决方案1】:

    默认情况下,Sequelize 会将 get/set/add/remove 方法添加到模型实例中。

    // All categories associated to userId
    User.findById(userId).getCategories()
    
    // All categories create by userId
    Category.findAll({
        where: {
            createdBy: userId
        }
    })
    

    【讨论】:

    • 这将为我提供与用户关联的所有类别。我不会收到(categories associated to user) + (categories created by user)
    【解决方案2】:

    应该是这样的

    myUser = User();
    myUser.categories();
    

    看看如何定义和查询 n:m 关系 续集: n:m

    【讨论】:

    • 这将为我提供与用户关联的所有类别。我不会收到(categories associated to user) + (categories created by user)
    【解决方案3】:

    试试这个:

    Category.belongsToMany(models.User, {through: 'CreateCategory'});
    
    User.belongsToMany(models.Category, {through: 'CreateCategory','foreignKey':'createdBy' });
    

    这将允许您定义与存储CategoryuserIdcreatedBy 字段的其他表的其他关系

    【讨论】:

    • hasMany 只会创建一对多关系,而不是多对多关系。 UserCategory 表是在我的情况下创建的,但我不知道如何使用 API 来实现我正在做的事情,而不是使用本机查询。
    • 如果你为两个表都设置了 'hasMany' 然后你创建了多对多关系然后你可以使用@jesusbv 正确说的函数
    • 这里的文档docs.sequelizejs.com/en/latest/docs/associations/#nmhasMany 声明为更具限制性的belongsToMany(我使用过;我没有使用belongsTo - 请参阅我的问题)而且我知道我可以使用 user.categories 获取类别的事实。但它只会给我与用户相关的类别。我想要一个(与用户相关的类别)+(用户创建的类别)的联合在 Sequelize 中似乎没有实现它的本地方法。
    最近更新 更多