协会续集3个表,多对多

Dav*_*vid 13 node.js sequelize.js

我有4张桌子

- client
- project
- user
- userProject
Run Code Online (Sandbox Code Playgroud)

一个项目属于客户端,它需要客户端外键client_id.

UserProject具有project_id和user_id外键,属于项目和用户.

一个用户拥有他的项目的客户.

  • 如何列出一个用户的客户端?

ole*_*hko 8

我想知道你可以使用sequalize的预先加载功能:

Client.findAll({
  include: [{
    model: Project,
    include: [{
      model: User,
      where: {
        id: <UserId>
      },
      required: false
    }]
  }]
}).then(function(clients) {
  /* ... */
});
Run Code Online (Sandbox Code Playgroud)


bol*_*lav 2

user这在和之间创建了多对多关系projectuser因此与你之间client存在多对多对一的关系。续集不支持此功能。我会在User模型上创建一个实例方法,如下所示:

User = sequelize.define('user', {
  // ... definition of user ...
},{
  instanceMethods: {
    getClients: function()  { 
      return this.getProjects().then(function (projects) {
        var id_map = {};
        for (var i = 0; i < projects.length; i++) {
          id_map[projects[i].clientId] = 1;
        }
        return Client.findAll({
          where: { id: [Object.keys(id_map)] }
        });
      });
    }
  }
});
Run Code Online (Sandbox Code Playgroud)

然后当您有这样的用户实例时调用此函数来获取客户端:

user.getClients().then(function (clients) {
  console.log(clients);
});
Run Code Online (Sandbox Code Playgroud)