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

2

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)

Bak answered 24/8, 2010 at 1:8 Comment(0)
B
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);
Bak answered 25/8, 2010 at 0:50 Comment(2)
this is how it works for me, if any of you have a better alternative feels free to post it here.Bak
I believe this is the way it should be done. Also notice that instead of array_merge() you can use the Array helper: $results = Arr::merge($staffs, $managers);. Kind regards.Isia
C
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.

Charade answered 27/8, 2010 at 12:24 Comment(2)
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.Bak
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).Charade

© 2022 - 2024 — McMap. All rights reserved.