【问题标题】:How to get two tables data in Node.js with object inside other object如何在Node.js中获取两个表数据,对象在另一个对象中
【发布时间】:2019-08-24 03:37:55
【问题描述】:

我有两张表,我需要这种格式的数据。这怎么可能?

My Tables

所需输出

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

一般我用它来从单个表中获取数据

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

【问题讨论】:

  • 什么是connection.query?你用什么模块来访问你的数据库?
  • 我正在使用 mysql @JordanRunning

标签: sql node.js


【解决方案1】:

我的解决方案:

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

【讨论】:

    【解决方案2】:

    我会使用 ORM 而不是自己编写查询。检查此link 用于项目节省了大量时间并且代码更干净。

    【讨论】:

    • 查看link 在 Sequelize 中加入两个表
    • 这是我的客户要求,我无法将其更改为某些 ORM @Bharath
    猜你喜欢
    • 2021-11-09
    • 1970-01-01
    • 2018-10-10
    • 2019-05-18
    • 2012-11-25
    • 1970-01-01
    • 1970-01-01
    • 2019-12-22
    • 1970-01-01
    相关资源
    最近更新 更多