2012-06-01 87 views
0

可以說我有3個模型,一,二和三。Kohana ORM has_many belongs_to

Model One有很多Three,Model Two有很多Three,Three屬於One和Two。

型號:

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.一種具有標題1,2,3,和B具有標題4.

問題是echo $ getThree-> one-> one_author;將回顯A,B,NULL,NULL。

如何正確回顯信息?

回答

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

PSforeign_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; 
} 
+0

如果將一個,兩個,三個用戶,類別,帖子分別替換爲什麼。你提出的設置是否有意義?我正在努力使關係有意義。 – markerpower

+0

您是否閱讀過官方文檔? http://kohanaframework.org/3.2/guide/orm/relationships#hasmany-through – biakaveron

+0

當然有許多次與其他例子相同。我只是不知道如何處理我正在做的事情。我不知道如何在帖子內呼叫用戶,當用戶與類別無關時,帖子只能有一個用戶。 – markerpower