the three tables I am trying to query are:
DB Structure:
roles_permissions: id, role_id, permission_id
user_roles: id, name, user_id
permissions: id, name
SQL Query
SELECT ur.name AS role_name,perm.name AS perm_name FROM user_roles AS ur
INNER JOIN roles_permissions as p
ON ur.id=p.role_id
INNER JOIN permissions AS perm
ON p.permission_id = perm.id
WHERE ur.user_id='$account_id'
Result from above query
array(11) {
[0]=>
array(2) {
["role_name"]=>
string(5) "Owner"
["perm_name"]=>
string(12) "view project"
}
[1]=>
array(2) {
["role_name"]=>
string(5) "Admin"
["perm_name"]=>
string(12) "edit project"
}
[2]=>
array(2) {
["role_name"]=>
string(6) "Editor"
["perm_name"]=>
string(14) "create project"
}
[3]=>
array(2) {
["role_name"]=>
string(5) "Owner"
["perm_name"]=>
string(12) "view project"
}
[4]=>
array(2) {
["role_name"]=>
string(5) "Admin"
["perm_name"]=>
string(12) "edit project"
}
[5]=>
array(2) {
["role_name"]=>
string(6) "Editor"
["perm_name"]=>
string(14) "create project"
}
[6]=>
array(2) {
["role_name"]=>
string(5) "Owner"
["perm_name"]=>
string(12) "view project"
}
[7]=>
array(2) {
["role_name"]=>
string(6) "Editor"
["perm_name"]=>
string(12) "edit project"
}
[8]=>
array(2) {
["role_name"]=>
string(5) "Owner"
["perm_name"]=>
string(12) "view project"
}
[9]=>
array(2) {
["role_name"]=>
string(5) "Admin"
["perm_name"]=>
string(12) "edit project"
}
[10]=>
array(2) {
["role_name"]=>
string(6) "Editor"
["perm_name"]=>
string(14) "create project"
}
}
What I am trying to do is select all user_roles assigned to a specific user_id, then get the permission ids assigned to that role from roles_permissions, then get the names of each permission from the permissions table. I would like to group by user_roles.name
so the resulting array would be
array(3) {
["Owner"]=>
array(3) {
["perm_name"]=>
string(12) "view project"
["perm_name"]=>
string(12) "create project"
["perm_name"]=>
string(12) "edit project"
}
["Editor"]=>
array(2) {
["perm_name"]=>
string(12) "view project"
["perm_name"]=>
string(12) "edit project"
}
["Admin"]=>
array(3) {
["perm_name"]=>
string(12) "view project"
["perm_name"]=>
string(12) "create project"
["perm_name"]=>
string(12) "edit project"
}
}
So if anyone can help that would be great, also looking to learn from this so if you could explain it for me that would be awesome.
Thanks
SQL FIDDLE : http://sqlfiddle.com/#!2/a7954/1
This won’t directly solve your problem, but your schema has a number of issues. Chief among them is that the tuple
(role_id, permission_id)inroles_permissionsisn’t unique. Here’s how I’d restructure things:(note that if you’re attempting to do permission groups or role hierarchies this gets more complicated)
The modified example fiddle showing the setup, with sample data.