2011-08-05 37 views
0

我有一個樁模型(MySQL表),並且結構是一樣的東西:CakePHP子查詢,如何?

id, parent, user_id, title, desc, created, modified 

談話的單個線程由一個帖子,隨後所有後續的帖子,其中post.parent原來POST_ID匹配。 user_32和user_40之間

樣品對話:和

110, 0, 32, thread_title, sample_description_here, created_time, modified_time 
121, 110, 40, comment_title, sample_comment_here, created_time, modified_time 
130, 110, 32, comment_title, sample_comment_here, created_time, modified_time 
140, 110, 32, comment_title, sample_comment_here, created_time, modified_time 
166, 110, 40, comment_title, sample_comment_here, created_time, modified_time 
290, 110, 32, comment_title, sample_comment_here, created_time, modified_time 

用純PHP,我只是做了外部查詢,然後由內查詢,則呼應談話到屏幕上,但你如何使用CakePHP實現這一目標??

問題:

如何構建CakePHP的查詢,顯示組成的單個對話(見上文)post_id_110,其次是所有後續帖裏post.parent == 110,由CREATED_TIME降序排序。 ??

回答

1

在Post模型的工作原理:

var $hasMany = array(
    'Children'=>array(
    'className' => 'Post', 
    'foreignKey' => 'parent_id' 
    ) 
); 

(在數據庫中將'parent'更改爲'parent_id',只是一個約定)。然後,在posts控制器:

$this->Post->find('first',array(
    'conditions'=>array(...), 
    'contain'=>array('Children') 
)); 

噢,並使用中容納。你並不真的需要這樣做,但它會使find()更清晰,並且在以後肯定會有所幫助。

+0

很酷,我該如何在視圖中繪製?我目前有一個foreach循環,但它不起作用,因爲我做了上述更改。謝謝 –

+0

只是打印出該find()的輸出來查看結果數組,並且可以循環查看結果數組。 –

1
在樁模型

var $belongsTo = array(
    'ParentPost' => array(
     'className' => 'Post', 
     'foreignKey' => 'parent_id', 
    ), 
) 

,然後用其他每個聯營模式

順便說一句 - PARENT_ID比父母更cakeish與支架

+0

嗨,你是什麼意思的「副模式」?在我的控制器中,我有$ this-> set('posts',$ this-> Post-> find('all',array('conditions'=> $ conditions)));那麼我現在怎麼讓對話顯示?謝謝 –

+0

http://book.cakephp.org/view/1039/Associations-Linking-Models-Together –