0

I need to select users having all given roles. In Model_User i have:

 public function getUsers() {

   $users = $this
            ->join('roles_users')->on('roles_users.user_id', '=', 'user.id')
            ->where('role_id', '=', ORM::factory('Role', array('name' => 'login')))
            ->and_where('role_id', '=', ORM::factory('Role', array('name' => 'simple_user')));

    return $users;
}

But this is not working. Regards.

masteryoda
  • 272
  • 2
  • 20
  • See this: http://stackoverflow.com/questions/3552875/kohana-3-auth-module-getting-users-with-staff-or-manager-role – Ryan Sep 05 '14 at 13:49
  • Thank You, but i know this question. I need to select users with both roles together ('and', not 'or'). Regards – masteryoda Sep 05 '14 at 14:20

2 Answers2

1

If you will follow link that Ryan posts you can modify that script this way:

public function get users() {

    $login = ORM::factory('role', array('name' => 'login'))->users->find_all()->as_array();
    $simple_user = ORM::factory('role', array('name' => 'simple_user'))->users->find_all()->as_array();

    return array_intersect($login, $simple_user);
}

Then as a result you should have only user that have both roles.

Another small thing is that you should follow kohana convention in your function name.

Grzesiek
  • 442
  • 4
  • 15
1

I'd suggest a different approach for this problem:

public function getUsers() {
    // Get IDs of all users having "login" role
    $active_users = ORM::factory('Role', array('name' => 'login'))->users->find_all()->as_array(null, 'id');
    // Select all users having roles "simple user" and "login"
    $users = ORM::factory('Role', array('name' => 'simple_user'))->users->where('id', 'IN', $active_users)->find_all();
    return $users;
}
di3sel
  • 2,002
  • 15
  • 24