如何使用Auth模块从Kohana 3中检索所有用户和所有角色?

时间:2017-02-28 08:41:38

标签: php mysql orm kohana kohana-3.3

我可以重新列出具有所有角色的所有用户的列表吗?我需要知道数据库中每个用户的所有角色。我在Kohana 3.3中使用Auth模块和ORM。

1 个答案:

答案 0 :(得分:0)

是的,你可以。但我无法理解为什么你想做这样的事情不是最理想的。

<强> 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