我无法让嵌套逻辑工作。我需要合并 2 个表中的数据并将其返回给请求。我不想要连接表,因为我需要先从 tableA 返回单个记录,然后在返回之前与 tableB 记录结合。下面是我的简化代码
exports.get_caution_reasons = async (req, res) => {
let return_data = [];
await db.sequelize.query("SELECT TableA xxxxx",{
type: QueryTypes.SELECT
}).then(recordA => {
for (let index = 0; index < recordA.length; index++) {
return_data.push({recordA[index].xxx, recordA[index].yyy})
db.sequelize.query("SELECT TableB xxxxx WHERE zzz=recordA.zzz",{
type: QueryTypes.SELECT
}).then(recordB => {
for (let index = 0; index < recordB.length; index++) {
return_data.push({recordB[index].xxx, recordB[index].yyy})
}
})
}
res.status(200).json({data: return_data});
})
};
它只返回 TableA 的记录。我尝试了各种异步并等待在那里获取 recordB 但没有成功。任何帮助都是有用的。
答案 0 :(得分:1)
可能是这样的:
exports.get_caution_reasons = async (req, res, next) => {
try {
let options = { type: QueryTypes.SELECT }
let data = []
let result_a = await db.sequelize.query("SELECT TableA xxxxx", options)
for (let index = 0; index < result_a.length; index++) {
data.push({ /* whatever you need... */ })
let result_b = await db.sequelize.query("SELECT TableB xxxxx WHERE zzz=recordA.zzz", options)
for (let index = 0; index < result_b.length; index++) {
data.push({ /* ... */ })
}
}
res.json({ data })
} catch (err) {
next(err)
}
}