1
我正在用Sequelize構建一個數據庫佈局作爲我的ORM。我有一個由用戶和應用程序模型組成的模型佈局。 用戶可以通過AppUsers表屬於許多應用程序(即可以訪問它們)。 一個應用程序屬於一個用戶。在Sequelize中加載belongsToMany關聯的結果
我已經在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()
查詢?謝謝!