findbyid()的for循环内部迭代后响应不正确

ykejflvf  于 2021-06-25  发布在  Mysql
关注(0)|答案(1)|浏览(256)

我创建了两个名为: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');
});

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

mm5n2pyu

mm5n2pyu1#

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

有关更多信息,请阅读sequelize association

相关问题