2011-06-10 53 views
0

我有一個用戶,消息和評論。Kohana 3.1 ORM:加入has_many

用戶ID user_id的

消息ID user_ID的

評論ID MESSAGE_ID

我可以用得到消息的用戶數據()。

$model = ORM::factory('message'); 
$messages = $model 
      ->with('user') 
      ->find_all(); 

('comment')不起作用。我猜是因爲它是爲一對一關係創建的,而我有has_many註釋消息。

如何獲得評論數據到$消息?如下所示:['message_id'] ['comment_id'] [DATA]?

回答

1

0定義的關係:

用戶的has_many消息 消息的has_many評論 消息belongs_to的用戶 評論belongs_to的消息

class Model_User extends ORM { 
    protected $_has_many = array('messages' => array()); 
} 

class Model_Message extends ORM { 
    protected $_belongs_to = array('user' => array()); 
    protected $_has_many = array('comments' => array()); 
} 

class Model_Comment extends ORM { 
    protected $_belongs_to = array('message' => array()); 
} 

1.使用用戶的消息:

$messages = ORM::factory('user', $user_id)->messages->find_all(); 
foreach($messages as $message) {...} 

2. Get消息店主:

$user = ORM::factory('message', $message_id)->user; // without find_all()! 

3 Get消息評論:

$comments = ORM::factory('message', $message_id)->comments->find_all(); 
foreach($comments as $comment) {...} 
+0

biakaveron,謝謝你爲你解答!我想我還不夠清楚。我對這些消息有評論,並希望讓它們與消息相同,即[message_id] => array([message_text]),array([comment])。爲了迭代他們在一個foreach而不是兩個。 – Fenec 2011-06-10 20:17:41

+0

你可以用'join'來做到這一點,但是原因是什麼?國際海事組織,少數小型數據庫請求比一個大型緩存更容易。添加新消息 - 你必須刷新整個緩存數據,而不是隻爲新消息添加緩存 – biakaveron 2011-06-11 19:17:20

+0

@biakaveron有一個類似的問題,對於我的(我承擔最多的)目的,當迭代消息對象時獲得的小DB請求並且執行'$ msg-> comments-> find_all()'是不可緩存的,因爲它們帶有消息ID,並且有成千上萬個。這樣做比單一'加入'查詢要慢得多,除非你想緩存整個數據集所有的RAM /磁盤,否則結果小的查詢是沒有用的 - 這對MySQL來說比Kohana好得多。 – Guss 2017-04-30 09:32:12