NodeJS/Knex创建Json响应 [英] NodeJS/Knex Creating Json Response

查看:150
本文介绍了NodeJS/Knex创建Json响应的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在使用带有knex(Postgresql)的NodeJS来存储数据库内容.

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

问题:

想象一下数据库中的以下两个表:

Imagine the following two tables in database:

表1

PROJECT
id (pk)
name

表2

EMPLOYEE
id (pk)
name
project_id (fk)

我想为用户创建一个类似于以下内容的json响应:

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'
       }
      ]
    }
  ] 
}

以此类推.

进行如下查询:

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

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

并且使用res.json()不会返回employees的数组.实现该目标的方法是什么?

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

推荐答案

SQL响应本质上是平面表,因此,除了knex之外,您还需要一个外部lib来将平面信息重构为嵌套对象.

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.

大多数ORM库都知道该怎么做.例如, objection.js 构建在knex之上使用.eager()来获取嵌套关系.使用objection.js ORM,查询将如下所示:Project.query().where('id', 1).eager('employees')

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

这篇关于NodeJS/Knex创建Json响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆