【问题标题】:Overlapping in NodeJS/mysql2NodeJS/mysql2 中的重叠
【发布时间】:2020-05-19 00:11:40
【问题描述】:

当我加入 2 个表时,我必须将结果作为嵌套数组在 nodejs 中使用 mysql2 进行操作

如果我正在执行

SELECT users.id as user_id , users.name as user_name , comments.id  as comment_id , comments.comment as comment FROM users LEFT JOIN comments ON comments.user_id = users.id WHERE users.id = 1

我得到的结果是

[{
"user_id" : 1,
"user_name" : "Naaban"
"comment_id" : "2",
"comment" : "Hello"
},
{
"user_id" : 1,
"user_name" : "Naaban"
"comment_id" : "3",
"comment" : "Bye"
}]

我的期望是

{
"user_id" : 1,
"user_name" : "ramesh",
"comments" : [
{
"comment_id" : 2,
"comment" : "Hello"
},
{
"comment_id" : 3,
"comment" : "Bye"
}]
}

【问题讨论】:

    标签: mysql node.js mysql2 node-mysql node-mysql2


    【解决方案1】:

    您可以直接从查询中执行此操作,但是您可以按如下方式规范您的代码:

    let data = [{
      user_id : 1,
      user_name : "Naaban",
      comment_id : "2",
      comment : "Hello"
      },
      {
      user_id : 1,
      user_name : "Naaban",
      comment_id : "3",
      comment : "Bye"
      }];
      
      let normalizedData = [];
      for(let i = 0; i < data.length; i++){
        const comment = {comment_id: data[i].comment_id, comment: data[i].comment};
        const { user_id, user_name} = data[i];
        normalizedData.push({ user_id, user_name, comment });
      }
      console.log(normalizedData);

    【讨论】:

    • 兄弟我需要查询结果,我在期待什么?但是你在 forloop 中渲染了结果,我不想在 for 循环中这样做......
    猜你喜欢
    • 2020-07-21
    • 2018-09-04
    • 2021-04-25
    • 1970-01-01
    • 2020-09-05
    • 2019-11-17
    • 2021-01-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多