Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Join across multiple junction tables with Sequelize

I have a database with three primary tables: users, teams, and folders joined by two junction tables, users_teams and teams_folders. There is a many-to-many relationship between users and teams and between teams and folders (a user can be on more than one team and teams can own more than one folder).

Sequelize does a wonderful job of managing the user-teams and teams-folder relationship, but I can find no way to establish a relationship between users and folders.

Is there any way to join across two junction tables without resorting to raw SQL?

There seems to be no way to accomplish this elegantly or in a reasonable number of steps. I have tried methods like user.getFolders(), Folder.findAll({ include: [User] }), but Sequelize doesn't seem to be able to understand a three level hierarchy.

like image 406
jtschoonhoven Avatar asked Sep 17 '14 00:09

jtschoonhoven


People also ask

How do I JOIN multiple tables in Sequelize in node JS?

There are two ways you can create JOIN queries and fetch data from multiple tables with Sequelize: Create raw SQL query using sequelize. query() method. Associate related Sequelize models and add the include option in your Sequelize query method.


2 Answers

Assuming the following relations:

User.belongsToMany(Team, { through: 'users_teams'}); Team.belongsToMany(User, { through: 'users_teams'});  Folder.belongsToMany(Team, { through: 'teams_folders'}); Team.belongsToMany(Folder, { through: 'teams_folders'}); 

You should be able to load everything in one go using nested includes:

User.findAll({   include: [     {       model: Team,        include: [         Folder       ]       }   ] }); 

You seem to be on the right track already with the example you have given in your post :). The only thing you need to change is instead of passing the User model directly in include, you pass an object with a model property and a further nested include property

like image 156
Jan Aagaard Meier Avatar answered Oct 04 '22 06:10

Jan Aagaard Meier


Pay attention to following:

  • Define relations in both directions
  • Check you have foreignKey, otherKey in correct order
User.belongsToMany(Team, {   through: 'users_teams',   foreignKey: 'user_id',   otherKey: 'team_id' });  Team.belongsToMany(User, {   through: 'users_teams',   foreignKey: 'team_id',   otherKey: 'user_id' }); 
like image 41
jmu Avatar answered Oct 04 '22 06:10

jmu