2016-12-25 95 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

我也很想知道是否有一種更簡單的方法在單個查詢而不是多個查詢中執行此操作。 –