Kohana ORM has_many belongs_to

时间:2012-06-01 01:14:04

标签: php orm kohana

假设我有3个模型,一个,两个和三个。

模型一有三个,模型二有三个,三个属于一个和两个。

型号:

class Model_One extends ORM {

protected $_primary_key = 'one_id';

protected $_has_many = array(
    'threes'=> array(
        'model' => 'three',                
        'through' => 'ones_threes',   
        'far_key' => 'three_id',       
        'foreign_key' => 'one_id'   
        ),
    );
}

class Model_Two extends ORM {

protected $_primary_key = 'two_id';

protected $_has_many = array(
    'threes'=> array(
        'model' => 'three',                
        'through' => 'twos_threes',   
        'far_key' => 'three_id',       
        'foreign_key' => 'two_id'   
        ),
    );
}

class Model_Three extends ORM {

protected $_primary_key = 'three_id';

protected $_belongs_to = array(
    'ones'=> array(
        'model' => 'one',                
        'through' => 'ones_threes',    
        'far_key' => 'one_id',       
        'foreign_key' => 'three_id'   
        ),

'twos'=> array(
        'model' => 'two',                
        'through' => 'twos_threes',    
        'far_key' => 'two_id',       
        'foreign_key' => 'three_id'   
        ),
);
}

我显示一,二,三。

$getTwos=ORM::factory('two')->find_all(); 

foreach($getTwos as $getTwo)
{
   echo $getTwo->two_category_title;
   foreach($getTwo->three->find_all() as $getThree)
   {
       echo $getThree->three_title;
       echo $getThree->one->one_author; 
   }
}

假设我有作者A和B以及标题1,标题2,标题3和标题4. A标题1,2,3和B标题为4.

问题是echo $ getThree-> one-> one_author;将回显A,B,NULL,NULL。

如何正确回显信息?

1 个答案:

答案 0 :(得分:1)

您的模型Three中的关系定义不正确。似乎One拥有并且属于许多Threes(HABTM或“有很多通过”),Two模型也是如此。这就是你需要的:

class Model_Three extends ORM {

protected $_primary_key = 'three_id';

protected $_has_many = array(
    'ones'=> array(
        'model' => 'one',                
        'through' => 'ones_threes',    
        'far_key' => 'one_id',       
        'foreign_key' => 'three_id'   
        ),

    'twos'=> array(
        'model' => 'two',                
        'through' => 'twos_threes',    
        'far_key' => 'two_id',       
        'foreign_key' => 'three_id'   
        ),
    );
}

<强> PS 即可。 foreign_key是可选的,因为您已在$_primary_key属性中定义它。

<强> PPS 即可。以下是“帖子仅属于一个用户”关系的示例:

class Model_User extends ORM {

   protected $_has_many = array(
      'posts' => array(),
   );
}

class Model_Post extends ORM {

   protected $_belongs_to = array(
      'author' => array(
          'model'       => 'user',
          // ignore if you have a `author_id` foreign key
          'foreign_key' => 'user_id', 
      ),
   );

   protected $_has_many = array(...);
}

// usage
$post = ORM::factory('post', 1);
echo $post->author->username;
$post->author = ORM::factory('user', 1);
$user = ORM::factory('user', 1);
foreach($user->posts->where('published', '=', 1)->find_all() as $posts) {
    echo $post->title;
}