SELECT id, name, created_at FROM users
SELECT name, description, user_role.user_id AS pivot_user_id, user_role.role_id AS pivot_role_id FROM roles INNER JOIN user_role ON roles.id = user_role.role_id WHERE user_role.user_id in (8, 10, 13, 1, 2)
users = users.map(user => {
user.roles = roles.filter(role => {
return (user.id === role.pivot_user_id) ? role : false;
});
return user;
});
[
{
"id": "8",
"name": "user_name_8",
"roles": []
},
{
"id": "1",
"name": "user_name_1",
"roles": [
{
"name": "role_name_3",
"pivot_user_id": "1",
"pivot_role_id": "3"
},
{
"name": "role_name_2",
"pivot_user_id": "1",
"pivot_role_id": "2"
}
]
},
{
"id": "2",
"name": "user_name_2",
"roles": [
{
"name": "role_name_2",
"pivot_user_id": "2",
"pivot_role_id": "2"
}
]
}
]