作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
使用 knex,如何从 users
表中获取用户的相关行以及 id=1 用户的所有组的数组?
...我正在运行此查询,但它为同一用户返回 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
目前正在返回:
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/
我是一名优秀的程序员,十分优秀!