2016-12-25 93 views
1

我有两个belongsToMany型号:Sequelize:根据关联的属于多个记录查找记录 - 但仍然返回所有关联的记录?

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)返回该约会的所有关联用户。

我有工作sequelize代码,不会(1):

var ret = connectors.Appts.findAll({ 
    include: [connectors.UserData], 
    where: {'$UserData.id$': args.originatingUserID} 
}).then((res) => res.map((item) => item.dataValues)); 

...但它仅用于返回一个指定的用户关联的用户数据。如何为每个约会返回所有关联用户的数据?

回答

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); 
      }); 
    } 

如果有更好的方法来做到这一点,请让我知道。

+0

我也很想知道是否有一种更简单的方法在单个查询而不是多个查询中执行此操作。 –