如何在belongsToMany中找到不属于特定ID的所有内容? [英] How to find all that don't belong to a specific id in belongsToMany?
问题描述
我有以下型号:
const users = sequelize.define('users', { /* definition */ }
const messageGroups = sequelize.define('message_groups', { /* definition */ }
它们是这样关联的:
models.messageGroups.belongsToMany(models.users, {through: 'user_message_groups'})
models.users.belongsToMany(models.messageGroups, {through: 'user_message_groups'})
如何返回不在具有特定 id 的 messageGroup 中的用户列表?
How can I return a list of users that are not in a messageGroup with a specific id?
例如,假设我的表格看起来像这样
For example, let's say my tables look like this
用户
id | 姓名 |
---|---|
1 | 脚 |
2 | 酒吧 |
3 | 巴兹 |
message_groups
message_groups
id | 姓名 |
---|---|
1 | 管理员 |
2 | 用户 |
user_message_groups
user_message_groups
用户 ID | messageGroupId |
---|---|
1 | 1 |
1 | 2 |
2 | 2 |
如果 message_groups id 为 1(管理员),我如何构造一个查询来返回 not 在该 message_group 中的两个用户?(应该返回用户 Bar
和 Baz
)
Given a message_groups id of 1 (Admin), how can I construct a query that returns the two users that are not in that message_group? (Should return users Bar
and Baz
)
推荐答案
如果您将 id 作为变量传递,一种选择是仅使用 users
和 user_message_groups
表.
If you are passing id as a variable, one option is to use just users
and user_message_groups
table.
首先,您需要 user_message_groups
的模型定义.
First, you need a model definition for user_message_groups
.
const userMessageGroups = sequelize.define('user_message_groups', {
userId: {
type: DataTypes.INTEGER,
allowNull: false
},
messageGroupId: {
type: DataTypes.INTEGER,
allowNull: false
}
});
接下来,在用户和 user_message_groups 表之间创建关联.
Next, create an association between users and user_message_groups table.
models.users.hasMany(models.userMessageGroups);
然后使用独占的 LEFT JOIN 查询.
Then query with exclusive LEFT JOIN.
models.users.findAll({
include: {
model: models.userMessageGroups,
required: false,
where: {
messageGroupId: 1
}
},
where: models.sequelize.literal('`user_message_groups.messageGroupId` IS NULL')
});
这篇关于如何在belongsToMany中找到不属于特定ID的所有内容?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!