我有一个post模型(mysql表),结构如下:
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 DESC 排序。??
最佳答案
在帖子模型中:
var $hasMany = array( 'Children'=>array( 'className' => 'Post', 'foreignKey' => 'parent_id' ) );
(并将数据库中的“parent”更改为“parent_id”,只是一个约定)。然后在帖子 Controller 中:
$this->Post->find('first',array( 'conditions'=>array(...), 'contain'=>array('Children') ));
哦,是的,使用 Containable。您实际上并不需要它来达到目的,但它使 find() 更清晰并且在以后绝对有帮助。
关于mysql - CakePHP 子查询,如何?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6962158/