首页 文章

Sequelize在多对多加入的地方

提问于
浏览
1

我希望有人可以帮助我 . 我正在使用Sequelize ORM for express.js,我在2个表之间有一个多对多的关系 .

为了简化我的查询,我们可以假装我的表是UserBook,UserBook和UserId,BookId和另一列(让我们说它的NoOfTimesRead)是User,Books和UserBooks .

我想做的是:

user.getBooks({
  where: {
    "userBooks.NoOfTimesRead": 0
  }
});

如果我输入:

user.getBooks();

这工作并返回所有书籍,我只是无法弄清楚如何通过连接表上的附加列进行查询 .

我希望这是有道理的,

谢谢参观!

1 回答

  • 2

    使用Belongs-To-Many,您可以根据关系查询并选择特定属性 . 例如,使用findAll with through

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

    基本上你可以使用 through 选项和 include 你链接的关系 . 更多可以找到here

相关问题