【问题标题】:Sequelize get all records if value exists on N:N table如果 N:N 表上存在值,则继续获取所有记录
【发布时间】:2022-01-28 14:11:05
【问题描述】:

我想用 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 查询示例中所做的那样

【问题讨论】:

  • 那么您是想按userId 还是按groupId 过滤,正如我在这里看到的groupId = ${group} 一样?
  • @Anatoly 我想同时过滤(userId 和 groupId),但我不知道如何在子查询中引用 User 表的 id,就像我从一开始在 SQL 查询中所做的那样
  • @shawnt00 如果我将 UserGroups 模型添加到包含数组,我会收到 SequelizeEagerLoadingError,我认为这是因为表是 N:N 并且 false 中的必需选项没有帮助
  • 您需要将此子查询条件移至用户条件,因为您有AND userId = U.id

标签: node.js sql-server sequelize.js


【解决方案1】:

您需要将此子查询条件移至用户条件,因为您有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] 表别名

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-06
    • 1970-01-01
    相关资源
    最近更新 更多