2011-08-05 32 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 –