我有两个belongsToMany模型:
const apptsModel = db.define('Appts', {
id: {type: Sequelize.INTEGER, primaryKey: true, autoIncrement: true},
[.....]
});
const UserDataModel = db.define('UserData', {
id: {type: Sequelize.STRING, primaryKey: true},
gender: {type: Sequelize.STRING},
name_title: {type: Sequelize.STRING},
name_first: {type: Sequelize.STRING},
name_last: {type: Sequelize.STRING},
[.....]
});
apptsModel.belongsToMany(UserDataModel, {through: 'ApptsToUsers'});
UserDataModel.belongsToMany(apptsModel, {through: 'ApptsToUsers'});
我想进行搜索:
1)查找至少有一个关联用户具有特定用户ID的所有约会。
2)返回该约会的所有关联用户。
我有工作的续集代码(1):
var ret = connectors.Appts.findAll({
include: [connectors.UserData],
where: {'$UserData.id$': args.originatingUserID}
}).then((res) => res.map((item) => item.dataValues));
...但它只返回指定用户的关联用户数据。如何为每个约会返回所有关联用户的数据?
答案 0 :(得分:0)
似乎还没有关于如何做到这一点的大量文档。这是有效的,所以我将在此处发布以供参考。
getAllApptsForCurrentUser(_, args) {
return Promise.resolve()
.then(() => {
//find all appointments and find those for which at least one
//participating user is the one specified in originatingUserID
var appts = connectors.Appts.findAll({
include: [{
model: connectors.UserData,
where: {id: args.originatingUserID}
}],
}).then((res) => res.map((item) => item.dataValues));
return appts;
})
.then(appts => {
//iterate returned appointments and perform a subquery on each,
//finding the other participating users
var arrayOfPromises = [];
appts.forEach(function (appt) {
arrayOfPromises.push(
connectors.Appts.findOne({where: {id: appt.id}, order: [['apptDateTime']], include: [ connectors.UserData ] })
);
});
//Promise.all returns true when all promises passed to it have
//returned true, or when one of them returns false
return Promise.all(arrayOfPromises);
})
.then(apptsWithJoinedData => {
//console.log(apptsWithJoinedData);
return apptsWithJoinedData;
})
.catch((err)=> {
console.log(err);
});
}
如果有更好的方法,请告诉我。