Reputation: 81
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!
Upvotes: 6
Views: 5033
Reputation: 1414
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
Upvotes: 4