1

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});
          }
       });
    })

2 Answers2

1

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) });
      }
   });
})
0

I would use an ORM instead of writing query myself. Check this link used for a project saved lot of time and code was cleaner.

Bharath
  • 390
  • 1
  • 6