node.js 使用 Sequelize 连接多个连接表

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25880539/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 17:52:58  来源:igfitidea点击:

Join across multiple junction tables with Sequelize

node.jssequelize.js

提问by jtschoonhoven

I have a database with three primary tables: users, teams, and foldersjoined by two junction tables, users_teamsand 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).

我有一个包含三个主表的数据库:users, teams,folders并由两个连接表连接,users_teamsteams_folders. 用户与团队之间以及团队与文件夹之间存在多对多关系(一个用户可以在多个团队中,而团队可以拥有多个文件夹)。

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.

Sequelize 在管理用户-团队和团队-文件夹关系方面做得非常出色,但我找不到在用户和文件夹之间建立关系的方法。

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

有没有办法在不使用原始 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.

似乎没有办法优雅地或以合理的步骤数来完成这一点。我尝试过像user.getFolders(), 之类的方法Folder.findAll({ include: [User] }),但是 Sequelize 似乎无法理解三级层次结构。

回答by Jan Aagaard Meier

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

您似乎已经在您的帖子中给出的示例中走上了正确的轨道:)。您唯一需要更改的是,不是直接在 中传递 User 模型include,而是传递具有模型属性和进一步嵌套的包含属性的对象

回答by jmu

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'
});