【发布时间】: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