gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 15:35:45 25 4
gpt4 key购买 nike

我正在构建的 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com