在for循环中迭代后,findById()的响应不正确

时间:2018-01-09 07:27:42

标签: mysql node.js express sequelize.js

我创建了两个名为:groupusermaps和groups的表。从groupusermaps我获取所有groupId和这些groupId我传入findById()方法来获取for循环中与该groupId相关的所有细节。

这是我的服务方法:

getAllGroupsByUserId(userId, callback) {
    var arr = [];
    return sequelize.transaction().then(function(t) {
        return groupUserMapModel.GroupUserMap.findAll({
            where: {
                userId: userId
            },
            transaction: t
        }).then((allGroupsByUserId) => {//from findAll i am getting 2, 1, 4 
groupId
            for (var p in allGroupsByUserId) {
                return 
groupModel.Group.findById(allGroupsByUserId[p].groupId, { transaction: t 
}).then((group) => {
                    arr.push(
                        JSON.stringify(group)
                    );
                });
            }
        }).then(() => {
            callback(arr);
        });
    });
}

我的控制器代码:

router.get('/controllers/getGroups/user/:userId/groups', (req, res) => {
groupService.getAllGroupsByUserId((req.params.userId), (result) => {
    log.info('Group list: ' + JSON.stringify(result));
});
res.send('Fetched all group list');
});

但是我从控制台上的控制器得到一个空数组作为响应。有没有办法解决这个问题?

1 个答案:

答案 0 :(得分:0)

groupUserMapModel.GroupUserMap.findAll({
  where: {
      userId: userId
  },
  include:[{
        model:groupModel
    }]
})
.then((results) => {
    console.log(results);
})
.catch(err=>{
    console.log(err);
})
//  provided that groupUserMapModel associated to   groupModel
groupUserMapModel.associate = models => {
    groupUserMapModel.belongsTo(models.groupModel, {foreignKey: groupId})
}

了解更多关于续集关联的信息