使用knex,如何从users表中获取用户的相关行以及id = 1的用户的所有组的数组?

这是我的users表:javascript - 使用Knex,如何将联接表的相关行作为嵌套对象给出?-LMLPHP

这是我的groups表:javascript - 使用Knex,如何将联接表的相关行作为嵌套对象给出?-LMLPHP

这是我的users_groups关联表:javascript - 使用Knex,如何将联接表的相关行作为嵌套对象给出?-LMLPHP

…我正在运行此查询,但它为同一用户返回3个单独的行:

db("users").join("users_groups", "users.id", "=", "users_groups.user_id").join("groups", "groups.id", "=", "users_groups.group_id").where("users.id", "=", 1)


我相信可以翻译成:

select * from users inner join users_groups on users.id = users_groups.user_id inner join groups on groups.id = users_groups.group_id where users.id=1


SQL返回:javascript - 使用Knex,如何将联接表的相关行作为嵌套对象给出?-LMLPHP

目前正在返回:

Array(3) [Object, Object, Object]
length:3
__proto__:Array(0) [, …]
0:Object {email:"[email protected]" group_id:1, id:1, name:"step 1", name:"r", role:"superadmin", user_id:1, username:"raj"}
1:Object {email:"[email protected]" group_id:2, id:1, name:"step 2", name:"r", role:"superadmin", user_id:1, username:"raj"}
2:Object {email:"[email protected]" group_id:3, id:1, name:"step 3", name:"r", role:"superadmin", user_id:1, username:"raj"}


串起来,看起来像这样

"[{"id":1,"name":"step 1","email":"[email protected]","username":"raj","password":"$2b$10$GbbLTP2sEPS7OKmR4l8RSeX/PUmoIFyNBJb1RIIIrbZa1NNwolHFK","role":"superadmin","created_at":"2020-04-14T12:45:38.138Z","user_id":1,"group_id":1},{"id":2,"name":"step 2","email":"[email protected]","username":"raj","password":"$2b$10$GbbLTP2sEPS7OKmR4l8RSeX/PUmoIFyNBJb1RIIIrbZa1NNwolHFK","role":"superadmin","created_at":"2020-04-14T12:45:38.138Z","user_id":1,"group_id":2},{"id":3,"name":"step 3","email":"[email protected]","username":"raj","password":"$2b$10$GbbLTP2sEPS7OKmR4l8RSeX/PUmoIFyNBJb1RIIIrbZa1NNwolHFK","role":"superadmin","created_at":"2020-04-14T12:45:38.138Z","user_id":1,"group_id":3}]"


我希望它返回一个表示单个用户行的对象,并为groups表中的3个相关行提供一个嵌套对象。例如:

{id:1, name:"raj", groups:[{id:1, name:"step 1"}, {id:2,name:"step 2"}, {id:3,name:"step 3"}]}


这可能吗?还是需要多个查询,这有多浪费?

最佳答案

Knex无法根据需要聚合平面数据。你应该自己做。

(await db('users')
  .join('users_groups', 'users.id', '=', 'users_groups.user_id')
  .join('groups', 'groups.id', '=', 'users_groups.group_id')
  .where('users.id', '=', 1)
  )
  .reduce((result, row) => {
    result[row.id] = result[row.id] || {
      id: row.id,
      username: row.username,
      email: row.email,
      groups: [],
    };

    result[row.id].groups.push({ id: row.group_id, name: row.name });
    return result;
  }, {});

关于javascript - 使用Knex,如何将联接表的相关行作为嵌套对象给出?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/61291269/

10-09 07:44