Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kohana 3 auth module, getting users with 'staff' or 'manager' role

I'm learning the framework, and now building an application using it.

I need to get all users that have 'user' or 'staff' role, but I couldn't find about it on the documentation.

Help anyone? (I think it's more an ORM problem the the auth module)

like image 466
leonardys Avatar asked Aug 24 '10 01:08

leonardys


2 Answers

I didn't find an easy way to do this using the ORM, but I have a workaround.
This is my code for anyone who might encounter the same problem with me.

// One for each role
$staffs = ORM::factory('role', array('name' => 'staff'))->users->find_all()->as_array();
$managers = ORM::factory('role', array('name' => 'manager'))->users->find_all()->as_array();

// Merge the results
$results = array_merge($staffs, $managers);
like image 100
leonardys Avatar answered Oct 04 '22 03:10

leonardys


May be you should create a separate ORM method for it? Something like this code:

public function get_users(array $roles)
{
    $users = DB::select(array($this->_has_many['roles']['foreign_key'], 'id'))
               ->distinct(TRUE)
               ->from($this->_has_many['roles']['through'])
               ->where($this->_has_many['roles']['far_key'], 'IN', DB::expr('('.implode(',', $roles).')'))
               ->execute($this->_db);
    if (count($users) == 0)
    {
        // return empty list
        return array();
    }
    // now we need only IDs from result
    $ids = array();
    foreach($users as $columns)
    {
        $ids[] = $columns['id'];
    }
    // load users by id
    return $this->where($this->_primary_key, 'IN', DB::expr('('.implode(',', $ids).')'))->find_all();
}

$roles is a role_id array (not names!). PS. I dont remember how to query 'WHERE IN', so I use DB expressions.

like image 44
biakaveron Avatar answered Oct 04 '22 03:10

biakaveron