Sort mysql results based on data from another table in Kohana
I inherited this Kohana project and have little experience with it and ORM.
Table structure is like this:
ROLES TABLE
id
name
ROLES_USERS TABLE
role_id
user_id
USERS TABLE
id
email
password
last_login
The thing is, I need to get users sorted by whether they have a certain role (login in this case) but have no idea how to do that with ORM.
Current query is:$users = ORM::factory('user')
->limit($pagination->items_per_page)
->offset($pagination->offset)
->order_by('last_login', 'DESC')
->find_all();
and then when outputting it's printed like this:
$row['status'][] = ($user->has('roles', ORM::factory('role', array('name' => 'login')))
? '<span class="green">Active</span>'
: '<spa开发者_开发知识库n class="red">Blocked</span>');
So the question would be how to alter the query to be able to sort by whether users are allowed to login or not.
$users = ORM::factory('user')
->join('roles_users', 'LEFT')
->on('roles_users.user_id', '=', 'user.id')
->join('roles', 'LEFT')
->on('roles_users.role_id', '=', DB::expr("roles.id AND roles.name = 'login'"))
->group_by('user.id')
->order_by('IFNULL("roles.id", \'2000\')', 'ASC')
->find_all()
I hope you don't have 2000 roles, but active users should come first using this query
Maybe you could just get the users for the login role?
$login_users = ORM::factory('role', array('name'=>'login'))->users->find_all();
精彩评论