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?
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
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With