douwei1408 2018-11-01 18:03
浏览 102
已采纳

mysql节点js带有while循环的动态数组

I have the following code in php it works great

if ($result = $mysqli->query("SELECT t.*, GROUP_CONCAT(c.category) categories, GROUP_CONCAT(k.keyword) keywords FROM dataclayTemplates t LEFT JOIN dataclayCategoryLink cl JOIN dataclayCategories c ON cl.categoryId=c.id ON t.id=cl.templateId LEFT JOIN dataclayKeywordLink kl JOIN dataclayKeywords k ON kl.keywordId=k.id ON t.id=kl.templateId GROUP BY t.id"))
{
  while($row = $result->fetch_array(MYSQLI_ASSOC)) {
    if($row["categories"] == null) {
      $row["categoryArray"] = [];
    } else {
      $row["categoryArray"] = array_unique(explode(",",$row["categories"]));
    }
    unset($row["categories"]);
    if($row["keywords"] == null) {
      $row["keywordArray"] = [];
    } else {
      $row["keywordArray"] = array_unique(explode(",",$row["keywords"]));
    }
    unset($row["keywords"]);
    $templateArray[] = $row;
  }
}

$result->close();

I want to do the same thing in nodejs using mysql (add a categoryArray array on the end of each result and fill it with the categories that are in each results categories) I have this node js code and a pull the data just fine I just need to build the categoryArray and keywordArray.

import express from 'express';
import connection from '../index.js'
const router = express.Router();
router.get('/allTemplates', function (req, res) {

    let queryString="SELECT t.*, GROUP_CONCAT(c.category) categories, GROUP_CONCAT(k.keyword) keywords FROM dataclayTemplates t LEFT JOIN dataclayCategoryLink cl JOIN dataclayCategories c ON cl.categoryId=c.id ON t.id=cl.templateId LEFT JOIN dataclayKeywordLink kl JOIN dataclayKeywords k ON kl.keywordId=k.id ON t.id=kl.templateId GROUP BY t.id";
    let query = connection.query(queryString, (error, result) => {
        if(error) {throw error;}
        res.json(result);
    })
});
module.exports = router;

below is my attempt to do it in nodejs however it does not work.

import express from 'express';
import connection from '../index.js'
const router = express.Router();
router.get('/allTemplates', function (req, res) {

    let queryString="SELECT t.*, GROUP_CONCAT(c.category) categories, GROUP_CONCAT(k.keyword) keywords FROM dataclayTemplates t LEFT JOIN dataclayCategoryLink cl JOIN dataclayCategories c ON cl.categoryId=c.id ON t.id=cl.templateId LEFT JOIN dataclayKeywordLink kl JOIN dataclayKeywords k ON kl.keywordId=k.id ON t.id=kl.templateId GROUP BY t.id";
    let query = connection.query(queryString, (error, result) => {
        if(error) {throw error;}
        let categoryArray=[];
        result.forEach(function(template){ 
        template.concat(categoryArray);
    template.categories.forEach(function(category) { 
        if(template.categories!=null){
      template.categoryArray.push(category);
        }
    });
});
    })
});
module.exports = router;

Any help would be great thanks.

  • 写回答

1条回答 默认 最新

  • dshxbrzgi090608692 2018-12-12 19:21
    关注

    I had to rework my code a bit but this is how i got it to work. Hope it helps someone else. Happy coding!

    router.get("/", async (req, res, next) => {
      const data = {};
      const sqlStatement =
        "SELECT t.*, GROUP_CONCAT(DISTINCT c.category) categories, GROUP_CONCAT(DISTINCT k.keyword) keywords FROM dataclayTemplates t LEFT JOIN dataclayCategoryLink cl JOIN dataclayCategories c ON cl.categoryId=c.id ON t.id=cl.templateId LEFT JOIN dataclayKeywordLink kl JOIN dataclayKeywords k ON kl.keywordId=k.id ON t.id=kl.templateId GROUP BY t.id;";
    
      try {
        data.categories = await database.query("SELECT * FROM dataclayCategories");
        data.keywords = await database.query("SELECT * FROM dataclayKeywords");
        data.templates = await database.query(sqlStatement);
        for (let i = 0; i < data.templates.length; i++) {
          const current = data.templates[i];
          if (current.categories) {
            current.categories = current.categories.split(",");
          }
          if (current.keywords) {
            current.keywords = current.keywords.split(",");
          }
        }
    
        res.json(data);
      } catch (error) {
        next(error);
      }
    });
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)
  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)