mysql - CakePHP 子查询,如何?

标签 mysql cakephp find

我有一个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/

相关文章:

shell - Unable to find the socket transport "ssl", CakePHP 从 shell 发送电子邮件

c++ - 为什么 std::find 不适用于 std::shared_ptr

jQuery 获取 div 内容

php - 如何从 MySQL 和 PHP 获取数组字符串

php - 如何计算 CakePHP 3.x 中 page() 使用的 OFFSET 值?

php - 用户 'www-data' @'localhost 的访问被拒绝 - 如何处理?

cakephp - 内联 TinyMCE 更改输入名称

java - 在从 Java 中的 URL 读取内容之前等到页面加载完毕

php - Codeigniter:查询在 select/like 语句中返回表中的所有行

MySQL 在 Drop Large Table 中挂起,现在需要很长时间才能连接