简体   繁体   中英

Sequelize where on many-to-many join

I am hoping somebody can help me. I am using the Sequelize ORM for express.js and I have a working many-to-many relationship between 2 tables.

For the sake of simplifying my query lets pretend my tables are Users, Books and UserBooks where UserBooks has UserId, BookId and an additional column (Lets say its NoOfTimesRead).

What I want to do is something like:

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

If I type:

user.getBooks();

This works and returns all books, I just haven't been able to figure out how to query this by the additional column on the joining table.

I hope this makes sense,

Thanks for taking a look!

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}
      }
   }] 
 });

Basically you can use through option and include the relationship that you linked. More can be found here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM