如何使用 Auth 模块从 Kohana 3 检索所有用户和所有角色?
How to retrieve all users and all roles from Kohana 3 using Auth module?
我可以收到具有所有角色的所有用户的列表吗?我需要知道数据库中每个用户的 all 角色。我在带有 ORM 的 Kohana 3.3 中使用 Auth 模块。
是的,你可以。但是我不明白你为什么要做这样次优的事情。
1.完整 ORM:
$users = ORM::factory('Auth_User')->find_all();
foreach($users as $user) {
$roles = $user->roles->find_all();
foreach($roles as $role)
$role->name;
}
2。通用 SQL(提示):
SELECT * FROM users
INNER JOIN user_roles USING(user_id)
INNER JOIN roles USING(role_id)
ORDER BY users.name
结果:
- user_1 role_1
- user_1 role_2
- user_2 role_x
3。易于显示SQL(但您在每次添加新角色时都更改代码)
SELECT users.*, IF(r1.user_id IS NULL, 0, 1) AS role1,
IF(r2.user_id IS NULL, 0, 1) AS role2,
IF(rn.user_id IS NULL, 0, 1) AS rolen
FROM users
LEFT JOIN (SELECT user_id FROM user_roles where role_id = 1) AS r1 USING(user_id)
LEFT JOIN (SELECT user_id FROM user_roles where role_id = 2) AS r2 USING(user_id)
LEFT JOIN (SELECT user_id FROM user_roles where role_id = n) AS rn USING(user_id)
结果:
username | role1 | role2 | rolen
user1 | 1 | 0 | 0
user2 | 0 | 1 | 1
我可以收到具有所有角色的所有用户的列表吗?我需要知道数据库中每个用户的 all 角色。我在带有 ORM 的 Kohana 3.3 中使用 Auth 模块。
是的,你可以。但是我不明白你为什么要做这样次优的事情。
1.完整 ORM:
$users = ORM::factory('Auth_User')->find_all();
foreach($users as $user) {
$roles = $user->roles->find_all();
foreach($roles as $role)
$role->name;
}
2。通用 SQL(提示):
SELECT * FROM users
INNER JOIN user_roles USING(user_id)
INNER JOIN roles USING(role_id)
ORDER BY users.name
结果:
- user_1 role_1
- user_1 role_2
- user_2 role_x
3。易于显示SQL(但您在每次添加新角色时都更改代码)
SELECT users.*, IF(r1.user_id IS NULL, 0, 1) AS role1,
IF(r2.user_id IS NULL, 0, 1) AS role2,
IF(rn.user_id IS NULL, 0, 1) AS rolen
FROM users
LEFT JOIN (SELECT user_id FROM user_roles where role_id = 1) AS r1 USING(user_id)
LEFT JOIN (SELECT user_id FROM user_roles where role_id = 2) AS r2 USING(user_id)
LEFT JOIN (SELECT user_id FROM user_roles where role_id = n) AS rn USING(user_id)
结果:
username | role1 | role2 | rolen
user1 | 1 | 0 | 0
user2 | 0 | 1 | 1