javascript - 如何在两个表之间使用sequelize创建嵌套请求

标签 javascript mysql sequelize.js

我正在构建的 Sequelize 后端中有两个表。第一个表是groups,第二个表是members。我想要:

最后,我想提交一个包含用户 ID 的 api 请求。然后,它将从 members 表中获取所有记录,并为每条记录获取在 members 表中作为外键引用的组。然后我想将组记录返回到前端。

有没有办法直接通过外键抓取外键记录还是需要发出两次请求?

这是我的代码:

路由器:

router.route('/user_groups/:userId')
    .get(memberController.getUserMember)

Controller :

    getUserMember: (req, res) => {
        let group_list = [];
        let user_id = req.params.userId
        Member.findAll({ where: { userId: user_id } })
            .then((response) => {
                for(let i = 0; i < response.length; i++){
                    Group.findByPk(response[i]['groupId'])
                        .then((group) => {
                            console.log(JSON.stringify(group))
                            group_list.push(group)
                        })
                        .catch((err) => {
                            console.log('Getting Group by Id error: ' + JSON.stringify(err))
                        })
                }
                console.log(group_list)
                res.status(200).send(data)
            })
            .catch((err) => {
                console.log('Getting member by Id error: ' + JSON.stringify(err))
            })
    },

the first request gets all of the member records containing the userId the second request within the then function will cycle through the members and grab the groups for each record based on its Id through the foreign key each of the records are that is returned from the group request is supposed to be stored in an array and then the array will be returned at the end....

对象没有存储在数组中,并且数组没有被返回。不知道该怎么办。

模范成员(member):

const Member = database.define(
    "member",
    {
        id: {type: seq.INTEGER, primaryKey: true, autoIncrement: true},
        balance: {type: seq.FLOAT(9, 2), allowNull: true, defaultValues: '0.00', 
                validate: {isFloat: true}
        },
        open_tabs: {type: seq.INTEGER, allowNull: false, defaultValues: '0', 
                 validate: {isInt: true}
        },
        reference: {type: seq.STRING, allowNull: false, 
                 validate: {isAlphanumeric: true}
        },
        admin: {type: seq.BOOLEAN, allowNull: false, defaultValues: false, 
              validate: {isIn: [['true', 'false']]}
        },
        active: {type: seq.BOOLEAN, allowNull: false, defaultValues: false, 
              validate: {isIn: [['true', 'false']]}
        },
    },
    {
        createdAt:  seq.DATE,
        updatedAt:  seq.DATE,
    }
)


Member.belongsTo(Group)
Member.belongsTo(User)

模型组:

const Group = database.define(
    "group",
    {
        id: {type: seq.INTEGER, primaryKey: true, autoIncrement: true},
        name: {type: seq.STRING, allowNull: false, 
             validate: {}
        },
        description: {type: seq.TEXT, allowNull: true, 
                validate: {}
        },
//        icon: {type: seq.STRING, allowNull: false, 
//               validate: {}
//        },
        members: {type: seq.INTEGER, allowNull: false, 
                 validate: {isInt: true}
        },
        reference: {type: seq.STRING, allowNull: false, 
                 validate: {isAlphanumeric: true}
        },
        active: {type: seq.BOOLEAN, allowNull: false, defaultValues: false, 
              validate: {isIn: [['true', 'false']]}
        },
    },
    {
        createdAt:  seq.DATE,
        updatedAt:  seq.DATE,
    }
)


Group.belongsTo(User, {as: "Host"})

最佳答案

基本问题是循环将在所有 Group.findByPk() 请求完成之前完成,并且一旦循环完成,数组就会被发送......但数组仍然是空的!

映射一个 Group.findByPk() promise 数组,并在之后使用 Promise.all() 执行 send()所有这些 promise 都已兑现

类似于:

getUserMember: (req, res) => {

        let user_id = req.params.userId
        Member.findAll({ where: { userId: user_id } })
            .then((response) => {
                 const groupPromises = response.map(member=>{
                      return Group.findByPk(member['groupId']).then(groups=>{
                         member.groups = groups;
                         return member;
                      }); 
                 });
                 return Promise.all(groupPromises).then(data=>res.status(200).send(data))

            })
            .catch((err) => {
                console.log('Something went wrong in one of the steps ' + JSON.stringify(err))
            })
    },

我假设您想要一个包含原始成员对象的数组,并将组作为属性groups分配给每个对象

关于javascript - 如何在两个表之间使用sequelize创建嵌套请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58253496/

相关文章:

mysql - 为什么 MySQL unix 时间没有达到 32 位无符号整数限制?

sql - 按位置和顺序对复杂的聚合属性进行 Sequelize

sequelize.js - 在 sequelize where 中使用用户输入作为列名是否安全?

mysql - 带计数的子选择

javascript - 创建了我自己的华氏温度到摄氏度转换器。但为什么它不起作用?

javascript - Rails 指定 javascript 文件的加载顺序?

Javascript 30 秒控制台倒计时器

javascript - 我可以在这里使用 Javascript 闭包而不是全局变量吗?

mysql - 获取测试运行的计数及其开始时间

MySQL CSV 导入失败 - "Data too long for column ' air_date' 在第 1 行”