简体   繁体   English

Kohana 3 ORM-使用静态方法联接和has_many关系

[英]Kohana 3 ORM - joins and has_many relationships with static methods

I have Model_User which extends ORM, with a $_has_many relationship with roles: 我有Model_User扩展了ORM,并与角色具有$_has_many关系:

protected $_has_many = array(
    'roles' => array('model'=>'role','through'=>'users_roles'),
);

I have a static function return all active users: 我有一个静态函数返回所有活动用户:

public static function get_all_active_users()
{
    return self::factory('user')->where('status', '=', 'active')->find_all();
}

I would like to update the function to return only users of a specific role, based on the following sql: 我想根据以下sql更新该函数以仅返回具有特定角色的用户:

SELECT `users`.* FROM `users`
INNER JOIN `users_roles` ON `users_roles`.`user_id` = `users`.`id`
INNER JOIN `roles` ON `roles`.`id` = `users_roles`.`role_id` AND `roles`.`identifier` = 'admin'
WHERE `users`.`status` = 'active'

Is there a way to filter the results within the get_all_active_users method or should I create a new method and manually join? 有没有办法在get_all_active_users方法中过滤结果,还是应该创建一个新方法并手动加入?

This is working for me: 这为我工作:

return self::factory('user')
                ->join('users_roles', 'INNER')->on('users_roles.user_id', '=', 'user.id')
                ->join('roles', 'INNER')->on('roles.id', '=', 'users_roles.role_id')
                ->where(roles.identifier', '=', 'admin')
                ->where('status', '=', 'active')
                ->find_all();

Interested to know any alternatives. 有兴趣知道任何替代方法。

A much more elegant way is defining the Role model to have many users like this: 一种更优雅的方法是定义“角色模型”以具有许多这样的用户:

protected $_has_many = array(
  'users' => array('model'=>'user','through'=>'users_roles'),
);

and then fetching the users through the Role itself like this: 然后像这样通过角色本身获取用户:

return self::factory('role')
            ->where('identifier', '=', 'admin')
            ->users->
            ->where('status', '=', 'active')
            ->find_all();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM