gpt4 book ai didi

javascript - 是否可以在 sequelize 中基于关联进行查询?

转载 作者:搜寻专家 更新时间:2023-10-31 23:52:53 25 4
gpt4 key购买 nike

我建模了一个数据结构,其中“房间”和“用户”之间存在 n:m 关系。

现在我想删除/销毁一个房间。因此我想检查删除用户是否在房间里。

我有用户名和房间 ID。

我怎样才能在一个查询中完成它。基本上我的问题是可以在查询中做类似的事情:

Room.destroy({
where: {
//username in users
users: {$contains: { username: "some username" }}
}
})

这里的 users 是我的用户的“关联”。

最佳答案

考虑到您的用户模型定义为 User
这可能对您有帮助(或至少给您一个起点):

Room.destroy({
include: [{
model: User,
through: {
where: {username: "some username"}
}
}]
});

这在 Sequelize documentation 的 n:m 查询部分中有描述。 :

With Belongs-To-Many you can query based on through relation and select specific attributes. For example using findAll with through

User.findAll({
include: [{
model: Project,
through: {
attributes: ['createdAt', 'startedAt', 'finishedAt']
where: {completed: true}
}
}]
});

关于javascript - 是否可以在 sequelize 中基于关联进行查询?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36700473/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com