5

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)

leonardys
  • 504
  • 4
  • 10

2 Answers2

9

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
  • 504
  • 4
  • 10
1

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
  • 5,493
  • 1
  • 16
  • 20
  • 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 Aug 28 '10 at 09:05
  • 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 Aug 30 '10 at 06:08