【问题标题】:Nested relationships in Kohana 3 ORMKohana 3 ORM 中的嵌套关​​系
【发布时间】:2012-04-20 19:09:15
【问题描述】:

假设我在 Kohana 中有三个 ORM 模型。

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
{

}

我会通过调用ORM::factory('category')->find($id)->groups 来获取一个类别中的所有组。我会通过调用ORM::factory('group')->find($id)->users 找到组中的所有用户。如何找到一个类别中的所有用户?

【问题讨论】:

  • 通过查找所有类别组,然后查找这些组中的所有用户。

标签: php orm kohana kohana-3 relationships


【解决方案1】:

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

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

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

 ORM::factory('group', array('id', $id))->users->find_all();

【讨论】:

  • 如果id是主键,调用ORM::factory('category', $id)就够了
【解决方案2】:

在添加一个有很多通过关系后,你就可以使用ORM::factory('category', $id)->users->find_all()了:

class Model_Category extends ORM
{
    protected $_has_many = array(
        'users' => array('through' => 'groups'),
        // ...
    );
}

【讨论】:

    【解决方案3】:

    查找一个类别中的所有组

    $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();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-01-27
      • 2011-03-24
      • 2011-07-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多