1

Let's say I have three ORM models in Kohana.

class Model_Category extends ORM
{
    protected $_has_many = array(
        'groups'      => array(
            'model'       => 'group',
            'foreign_key' => 'category_id'
        )
    );
}

class Model_Group extends ORM
{
    protected $_has_many = array(
        'users'      => array(
            'model'       => 'user',
            'foreign_key' => 'group_id'
        )
    );
}

class Model_User extends ORM
{

}

I would get all the groups in a category by calling ORM::factory('category')->find($id)->groups. I would find all the users in a group by calling ORM::factory('group')->find($id)->users. How would I find all the users in a category?

4

3 回答 3

1

我会通过 callin 找到一个组中的所有用户

 $groups = ORM::factory('category', array('id', $id))->groups->find_all();

我如何找到一个类别中的所有用户?

 ORM::factory('group', array('id', $id))->users->find_all();
于 2012-04-21T08:52:44.327 回答
1

查找某个类别中的所有组

$groups = ORM::factory('category', $id)->groups->find_all();

遍历组并获取她的用户

foreach ($groups as $group) 
{
  $users = $group->users->find_all()
}

或者建立一个连接,像这样

 $users = DB::select('users.*')->from('categories')
     ->join('groups', 'LEFT')
     ->on('categories.id', '=', 'groups.category_id')
     ->join('users', 'LEFT')
     ->on('groups.id', '=', 'users.group_id')
     ->where('categories.id', '=', $id)
     ->execute();
于 2012-04-25T19:31:02.507 回答
1

ORM::factory('category', $id)->users->find_all()在添加了一个 has many through关系后,您将能够使用:

class Model_Category extends ORM
{
    protected $_has_many = array(
        'users' => array('through' => 'groups'),
        // ...
    );
}
于 2012-04-22T04:39:45.850 回答