我要查询的三个表是:
数据库结构:
roles_permissions: id, role_id, permission_id
user_roles: id, name, user_id
permissions: id, name
SQL 查询
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'
上述查询的结果
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"
}
}
我要做的是选择user_roles
分配给特定 user_id 的所有内容,然后从中获取分配给该角色的权限 ID roles_permissions
,然后从表中获取每个权限的名称permissions
。我想分组user_roles.name
所以结果数组将是
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"
}
}
因此,如果有人可以提供帮助,那就太好了,也希望从中学习,所以如果你能为我解释一下,那就太棒了。
谢谢
SQL FIDDLE:http ://sqlfiddle.com/#!2/a7954/1