Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sequelize Join Models Include many to many

Say I have three models like this

var User = _define('user', {
  username: Sequelize.INTEGER
});
var UserPubCrawl = _define('userpubcrawl', {
  user_id: Sequelize.STRING(64), // the user
  bar_id: Sequelize.INTEGER // 1 to many
});

var Bars = _define('bar', {
  name:  type: Sequelize.STRING,
}

The relationships are one meal

User(one) --> UserPubCrawl (to many) --> Bars(to many)

So 1 user can have multiple pubcrawls to many bars for a particular pub crawl I want to find all the bars that "Simpson" went to.

Do i need to change the model definitions, if so please show me? What would the findAll Query look like?

like image 248
Robert I Avatar asked Apr 14 '17 21:04

Robert I


1 Answers

If I understand your DB relationships right, it can be stated as:

1 user can visit many bars
1 bar can be visited by many users

So, in other words you've a many to many relationship between Users and Bars, with the JOIN table being UserPubCrawl.

If so, your model associations should look like:

User.belongsToMany(Bar, { through: UserPubCrawl });
Bar.belongsToMany(User, { through: UserPubCrawl });

And, finding out all the bars that Simpson went to, is really simple:

User.findAll({
  where: { user_id: '123' },
  include: {
    model: Bars,
    through: { attributes: [] } // this will remove the rows from the join table (i.e. 'UserPubCrawl table') in the result set
  }
});
like image 196
Adhyatmik Avatar answered Oct 09 '22 02:10

Adhyatmik