views:

235

answers:

2

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)

+2  A: 

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);
leonardys
this is how it works for me, if any of you have a better alternative feels free to post it here.
leonardys
A: 

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.

biakaveron
Manual sql query is always available, but I thought before that ORM can solve that problem out of the box. I don't have many experiences with the query builder, I look into it. Thanks for the alternative answer.
leonardys
As you can see, my code uses $this->_has_many['roles'] settings, so if you change related model or foreign_key, this method will work without any modification (instead of plain SQL queries).
biakaveron
Does `->where($this->_primary_key, 'IN', $ids)` not work?
pedro_sland