Join across multiple junction tables with Sequelize

前端 未结 2 1012
灰色年华
灰色年华 2021-01-31 03:17

I have a database with three primary tables: users, teams, and folders joined by two junction tables, users_teams and t

相关标签:
2条回答
  • 2021-01-31 04:15

    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

    0 讨论(0)
  • 2021-01-31 04:17

    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'
    });
    
    0 讨论(0)
提交回复
热议问题