NodeJS/Knex Creating Json Response

2019-03-03 09:25发布

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条回答
看我几分像从前
2楼-- · 2019-03-03 10:12

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

查看更多
登录 后发表回答