【问题标题】:Eagerly load result of a belongsToMany association in Sequelize急切加载 Sequelize 中的 belongsToMany 关联的结果
【发布时间】:2016-08-25 07:59:39
【问题描述】:

我目前正在构建一个使用 Sequelize 作为我的 ORM 的数据库布局。我有一个模型布局,其中包含一个用户和一个应用程序模型。 一个用户可以通过 AppUsers 表属于许多应用程序(即可以访问它们)。 一个应用属于一个用户。

我已经在这样的 App 模型中实现了这个

classMethods: {
  associate: function (models) {
    App.belongsTo(models.User, {
      foreignKey: 'id',
      constraints: false,
      as: 'owner'
    });

    App.belongsToMany(models.User, {
      through: {
        model: models.AppUser,
        unique: true
      },
      foreignKey: 'app_id',
      otherKey: 'user_id',
      constraints: false
    });
  }
}

在这样的用户模型中

classMethods: {
  associate: function (models) {
    User.belongsToMany(models.App, {
      through: {
        model: models.AppUser,
        unique: true
      },
      foreignKey: 'user_id',
      otherKey: 'app_id',
      constraints: false,
      as: 'apps'
    });

    User.hasMany(models.App, {
      foreignKey: 'owner_id',
      constraints: false,
      scope: {
        owner_type: 'user'
      },
      as: 'ownApps'
    });
  }
}

现在我的实际问题是: 我正在寻找一种方法来查询用户有权访问的应用程序(即user.getApps()),并快速加载所有者信息并已包含在对该查询的响应中。

我在User.belongsToMany(models.App, … 关联中使用过include:scope:,但它们都没有产生预期的结果。 有没有办法做到这一点,还是我需要编写一个自定义的App.findAll() 查询?谢谢!

【问题讨论】:

    标签: mysql node.js sequelize.js


    【解决方案1】:

    事实证明,答案相当简单: 只需将 include 添加到关联的模型函数即可:

    user.getApps({ include: [{ model: models.User, as: 'owner' }] })
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-07-28
      • 2018-01-17
      • 2015-02-24
      • 2018-05-29
      • 2021-02-07
      • 1970-01-01
      • 2019-02-03
      相关资源
      最近更新 更多