更改knex.js json输出的格式

时间:2019-05-10 14:35:34

标签: javascript node.js json knex.js

我的Node应用程序中有这个:

const query = db_connect.sequelize.knex.select([
      'managers.id',
      'managers.managername',
      'managers.email',
      'teams.teamname',
      'teams.id',
      db_connect.sequelize.knex.raw('COUNT(employees_managers.id)'),
    ]).from('managers')
      .leftJoin('employees_users', 'managers.id', 'employees_managers.managers_id')
      .leftJoin('teams_managers', 'managers.id', 'teams_managers.managers_id')
      .leftJoin('teams', 'teams.id', 'teams_managers.teams_id')
      .groupByRaw('managers.id, managers.managername, managers.email, teams.teamname');

它产生了这个:

{
    "managers": [
        {
            "id": 1,
            "name": "John Doe",
            "email": "johndoe@email.com",
            "teamname": "Team 1",
            "count": 2
        },
        {
            "id": 1,
            "name": "John Doe",
            "email": "johndoe@email.com",
            "teamname": "Team 2",
            "count": 2
        }
    ]
}

我想将其结构更改为如下形式:

{
    "managers": [
        {
            "id": 1,
            "name": "John Doe",
            "email": "johndoe@email.com",
            "teams": [
                {
                    "id": 1,
                    "name": "Team 1",
                    "TeamsManagers": {
                        "id": 1,
                        "managerId": 1
                    }
                },
                    {
                        "id": 1,
                        "name": "Team 2",
                        "TeamsManagers": {
                            "id": 1,
                            "managerId": 1
                        }
                    }
            ]
        }
    ]
}

如何更改knex响应的结构以上面的格式显示?我曾尝试查看bookeself.js,但不确定这是否是正确的工具。

0 个答案:

没有答案