gpt4 book ai didi

javascript - 使用 Knex,如何将连接表的相关行作为嵌套对象给出?

转载 作者:行者123 更新时间:2023-12-02 21:03:02 27 4
gpt4 key购买 nike

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

这是我的用户表:https://i.imgur.com/t2psBd4.png

这是我的表:enter image description here

这是我的users_groups关联表:enter image description here

...我正在运行此查询,但它为同一用户返回 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 返回:enter image description here

目前正在返回:

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

字符串化,看起来像这样

"[{"id":1,"name":"step 1","email":"raj@raj.raj","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":"raj@raj.raj","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":"raj@raj.raj","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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com