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

Is it possible in sequelize to query based on an association?

我建模了一个数据结构,其中 "Rooms" 和 "Users" 之间存在 n:m 关系。

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

我有用户名和房间号。

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

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

这里的用户是 "Association" 我的用户。

考虑到您的用户模型定义为 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}
      }
  }]
});