当我连接 2 个表时,我必须将结果作为嵌套数组获取,如何使用 mysql2 在 nodejs 中做到这一点
如果我正在执行
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"
}]
}
您可以直接从查询中执行此操作,但是您可以按如下方式规范化代码:
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);