0

假设我有 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 以及 Title 1、Title 2、Title 3 和 Title 4。A 有 Title 1、2、3,B 有 Title 4。

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

如何正确回显信息?

4

1 回答 1

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'   
        ),
    );
}

附言foreign_key是可选的,因为您已经在$_primary_key属性中定义了它。

聚苯乙烯。这是“帖子仅属于一个用户”关系的示例:

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;
}
于 2012-06-01T05:31:57.067 回答