我要查询的三个表是:
数据库结构:
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_id的所有user_roles
,然后从roles_permissions
获取分配给该角色的权限ID,然后从{{获取每个权限的名称1}}表。我想按permissions
所以生成的数组将是
user_roles.name
所以,如果有人可以提供帮助,那就太好了,也希望从中学习,如果你能为我解释那将是非常棒的。
由于
SQL FIDDLE:http://sqlfiddle.com/#!2/a7954/1
答案 0 :(得分:1)
您的测试数据错误,即role_id = 1的表role_permission中的user_role.id = 1(name = owner,user_id = 1)只有permission_id = 1(即视图);
答案 1 :(得分:1)
这不会直接解决您的问题,但您的架构存在许多问题。其中最主要的是(role_id, permission_id)
中的元组roles_permissions
并不是唯一的。以下是我如何重组事物:
role
==========
id -- autoincrement
name -- varchar
user_role
===========
role_id -- fk to role.id
user_id -- fk to user.id (not listed here, but you obviously have one)
permission
===========
id -- autoincrement
name -- varchar
role_permission
===================
role_id -- fk to role.id
permission_id -- fk to permission.id
(请注意,如果您尝试执行权限组或角色层次结构,则会变得更复杂)
The modified example fiddle显示设置,包含样本数据。
答案 2 :(得分:0)
如果没有看到表格结构,很难对此进行测试,但您是否尝试过添加:
group by ur.name, perm.name
order by ur.name
在where子句之后?