NodeJS/Knex Creating Json Response

2019-03-03 09:33发布

问题:

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')