我目前正在使用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()
查询?谢谢!
1 回答
事实证明,答案很简单:只需将
include
添加到相关的模型函数就可以了: