最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Sequelize where on many-to-many join - Stack Overflow

programmeradmin1浏览0评论

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!

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!

Share Improve this question asked Feb 3, 2016 at 17:39 Peter Andrew JonesPeter Andrew Jones 811 silver badge5 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 4

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: {pleted: true}
      }
   }] 
 });

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

发布评论

评论列表(0)

  1. 暂无评论