如何在belongsToMany中找到不属于特定ID的所有内容? [英] How to find all that don't belong to a specific id in belongsToMany?

查看:57
本文介绍了如何在belongsToMany中找到不属于特定ID的所有内容?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下型号:

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

<头>
用户 IDmessageGroupId
11
12
22

如果 message_groups id 为 1(管理员),我如何构造一个查询来返回 not 在该 message_group 中的两个用户?(应该返回用户 BarBaz)

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 作为变量传递,一种选择是仅使用 usersuser_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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆