【问题标题】:Association sequelize 3 tables, many to many关联 sequelize 3 个表,多对多
【发布时间】:2014-04-15 16:12:45
【问题描述】:

我有 4 张桌子

- client
- project
- user
- userProject

一个项目属于客户端,需要有客户端外键client_id。

UserProject有project_id和user_id外键,属于project和user。

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

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

【问题讨论】:

  • 请提供您尝试的方式和遇到的麻烦。
  • 我不知道怎么做。我以为你会告诉我一个方法来做到这一点。我理解 sequelize,我不会对 2 个表的简单关联有任何问题。

标签: node.js sequelize.js


【解决方案1】:

我想知道你可以使用sequalize 中的eager loading 功能:

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

【讨论】:

    【解决方案2】:

    这会在userproject 之间创建多对多关系。在userclient 之间,您因此具有多对多对一的关系。 sequelize 不支持此功能。我会像这样在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)] }
            });
          });
        }
      }
    });
    

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

    user.getClients().then(function (clients) {
      console.log(clients);
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-07-23
      • 1970-01-01
      • 2021-11-05
      • 1970-01-01
      相关资源
      最近更新 更多