nodejs+mysql嵌套查询的问题

2020.05.21记录小问题~

需求:返回所有分类,以及分类(id,name,img,desc...)下的所有商品(id,name,img)

最初想法:第一次执行sql拿到所有分类,第二次循环result,按每个分类ID执行sql获取对应的商品

现实:出现异步问题,第二次循环sql还没执行就res.json()了

怎么办呢,尝试了两种办法都有效的解决了问题!!

解决方案一:

       通过mysql的 GROUP_CONCAT 来解决,把所有商品的详情拼装成string,每个商品之间用特定符号分隔,类似网络请求时url的参数拼接思路

解决方案二:

  起初是考虑用async await异步实现,在一位评论区大佬那里受到了启发! 如下图

           

  突然想起来,join虽然会有很多行,看起来冗余,但是是可以通过node端处理掉成想要的格式的!

   参考代码贴出来!

 1      2       let categoryArr = []
 3       for (var i =0; i<result0.length; i++) {
 4         let Cid = result0[i].category_id
 5         console.log(Cid)
 6         let hasIndex = categoryArr.findIndex(item => item.category_id === Cid)
 7         console.log(hasIndex)
 8         if (hasIndex !== -1) {
 9           categoryArr[hasIndex].products.push({
10             product_id: result0[i].product_id,
11             product_name: result0[i].product_name,
12             main_img_url: result0[i].main_img_url
13           })
14         } else {
15           categoryArr.push({
16             category_id: result0[i].category_id,
17             category_name: result0[i].category_name,
18             description: result0[i].description,
19             url: result0[i].url,
20             products: [{
21               product_id: result0[i].product_id,
22               product_name: result0[i].product_name,
23               main_img_url: result0[i].main_img_url
24             }]
25           })
26         }
27       }

参考自: https://cloud.tencent.com/developer/ask/185664  评论区!

原文地址:https://www.cnblogs.com/zhuxingqing/p/12933843.html