我使用了nested query
格式,当我在 second console.log(main_array)
部分中打印db.query
时工作正常,这将在单个数组中返回parent_category和child类别,例如父子关系,但是当我发送全部数据outside of second query
部分时,它将仅返回parent category
而不是全部数据。
我在 nodeJs 中使用了以下脚本。
learnAPI: (req, res) => {
let query = "SELECT * FROM category where parent_id IS NULL";
const main_array = {};
var tets = {};
db.query(query, (err, result) => {
if (err) {
return res.status(500).send(err);
}
Object.keys(result).forEach(function (key) {
let cat_name = result[key]['name'];
main_array[cat_name] = result[key];
let getsubcategory = "SELECT * FROM category where parent_id = " + result[key]['id'];
db.query(getsubcategory, (err, subcategory) => {
Object.keys(subcategory).forEach(function (key) {
let sub_name = subcategory[key]['name'];
main_array[cat_name][sub_name] = subcategory[key];
});
tets = main_array;
});
console.log(tets);
});
res.setHeader('Content-Type', "application/json");
res.status(200).send(main_array);
});
},
任何人都知道我该怎么做到吗?
答案 0 :(得分:0)
尝试一下:
learnAPI: (req, res) => {
let query = "SELECT * FROM category where parent_id IS NULL";
let main_array = {};
let tets = [];
db.query(query, (err, result) => {
if (err) {
return res.status(500).send(err);
}
Object.keys(result).forEach(function (key) {
let cat_name = result[key]['name'];
main_array[cat_name] = result[key];
let getsubcategory = "SELECT * FROM category where parent_id = " + result[key]['id'];
db.query(getsubcategory, (err, subcategory) => {
Object.keys(subcategory).forEach(function (key) {
let sub_name = subcategory[key]['name'];
main_array[cat_name][sub_name] = subcategory[key];
});
tets.push(main_array);
});
console.log(tets);
});
res.setHeader('Content-Type', "application/json");
res.status(200).send(main_array);
});
}