【发布时间】: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