简体   繁体   English

如何在Node.js中获取两个表数据以及其他对象内部的对象

[英]How to get two tables data in Node.js with object inside other object

I have two tables and I need data in this format. 我有两个表,我需要这种格式的数据。 How is this Possible? 这怎么可能?

My Tables 我的桌子

Required Output 所需输出

{
  "id":"1",
  "name":"akhil",
  "pics": [
    {
      "pic1": "123.jpg",
      "pic2": "123.jpg"
    }
  ]
}

Generally I use this for getting data from single table 通常我用它来从单个表中获取数据

const express = require('express');
const app = express();
const jwt = require('jsonwebtoken');
const bcrypt = require('bcryptjs');
const config = require('./config');

var VerifyToken = require('./VerifyToken');

const mysql      = require('mysql');

app.use(express.json());
const connection = mysql.createConnection({
   host     : 'localhost',
   user     : 'root',
   password : 'password',
   database : 'sample'
});
    app.get('/usersdata', VerifyToken, (req, res) => {
       let id = req.userId;
       console.log(req.userId);
       connection.query("select * from users", function (error, results, fields) {
          if (error) throw error;
          else {
             res.send({"result": results});
          }
       });
    })

My Solution: 我的解决方案:

app.get('/usersdata', (req, res) => {
   connection.query("select u.id, u.name, p.pic1, p.pic2 from users u, pics p where u.usersid=p.id", function (error, results, fields) {
      if (error) throw error;
      else {
         let data = results;
         let newResult = {};
         results.map(row => {
            if(newResult[row.id]) {
               newResult[row.id].pics.push(row.pic1, row.pic2)
            } else {
               newResult[row.id] = { id: row.id, name: row.name, pics: [row.pic1, row.pic2] };
            }
         })
         res.send({ "result": Object.values(newResult) });
      }
   });
})

I would use an ORM instead of writing query myself. 我将使用ORM而不是自己编写查询。 Check this link used for a project saved lot of time and code was cleaner. 检查此链接可为项目节省大量时间,并使代码更干净。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM