NodeJS/Knex Creating Json Response

本小妞迷上赌 提交于 2019-12-02 09:42:11

问题


I'm currently using NodeJS with knex (Postgresql) for database stuff.

Problem:

Imagine the following two tables in database:

Table 1


PROJECT
id (pk)
name

Table 2


EMPLOYEE
id (pk)
name
project_id (fk)

I want to create a json-response to the user that looks like the following:

{
  projects: [
    {
      id: 1,
      name: 'emxample 1',
      employees: [
       {
         id: 1,
         name: 'example 1'
       },
       {
         id: 2,
         name: 'example 2'
       }
      ]
    }
  ] 
}

and so on.

Making a query like:

let query = knex('project').select('project.*', 'employee.*').join('employee', 'employee.project_id', '=', 'project.id');

query.then((projects) => { res.json(projects); }); 

And using res.json() does not return an array of employees. What is the way to go to achieve that?


回答1:


SQL responses are flat tables by their nature so in addition to knex you will need an external lib which can reconstruct flat information to nested objects.

Most of the ORM libraries know how to do it. For example objection.js which is built on top of knex uses .eager() to fetch nested relations. With objection.js ORM the query would look like this Project.query().where('id', 1).eager('employees')



来源:https://stackoverflow.com/questions/51557391/nodejs-knex-creating-json-response

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!