如果 N:N table 上存在值,则 Sequelize 获取所有记录

Sequelize get all records if value exists on N:N table

我想用sequelize实现这个查询

SELECT U.username, G.groupName
FROM [user] U INNER JOIN [userGroup] UG ON (U.id = UG.userId) INNER JOIN [group] G ON (G.id = UG.groupId)
WHERE U.profileId = @profile AND EXISTS (SELECT groupId FROM [userGroup] WHERE groupId = @group AND userId = U.id)

预期结果是与配置文件匹配的所有用户以及他们的所有组,其中应存在某些组

这是我关联层的相关代码

db.users.belongsToMany(db.group, {
  as: 'Groups',
  through: UserGroup,
  foreignKey: 'userId',
  otherKey: 'groupId',
});
db.group.belongsToMany(db.users, {
  as: 'Users',
  through: UserGroup,
  foreignKey: 'groupId',
  otherKey: 'userId',
});

和来自控制器的那个

User.findAll({
   where: {profileId = Number(profileType)},
   include: [{
      model: Group,
      as: 'Groups',
      attributes: ['groupName'],
      where: [
        {
          [Op.and]: sequelize.literal(
            `EXISTS (SELECT [UG].groupId FROM [userGroup] AS [UG] WHERE [UG].groupId = ${group})`
          ),
        };
      ]
      required: true,
   }]

我的主要问题是如何在 sequelize 子查询中按 userId 进行过滤,就像我从一开始就在 SQL 查询示例中所做的那样

您需要将此子查询条件移动到用户条件中,因为您有AND userId = U.id。像这样:

User.findAll({
   where: {
      [Op.and]: [{
        profileId = Number(profileType)
      }, 
      sequelize.literal(
            `EXISTS (SELECT [UG].groupId FROM [userGroup] AS [UG] WHERE [UG].groupId = ${group} AND [UG].userId=[User].id)`
          )]
   },
   include: [{
      model: Group,
      as: 'Groups',
      attributes: ['groupName'],
      required: true,
   }]

您应该查看生成的 SQL 查询,并根据需要在 AND [UG].userId=[User].id

中更正 [User] table 别名