使用CakePHP中的最新评论检索帖子

时间:2011-02-23 15:29:24

标签: cakephp cakephp-appmodel cakephp-2.x

我说模型Post和模型Comment如下:

Post hasMany Comment 
Comment belongsTo Post

如何使用find('all')检索每个Post及其关联的最新Comment

我尝试在hasOne中定义Post关系:

var $hasOne = array('LatestComment' => array('className' => 'Comment', 'order' => 'LatestComment.created DESC'));

但是当我执行Post->find('all')时,它会多次返回Post次,每次Comment一次,LatestComment设置为不同的Comments。< / p>

2 个答案:

答案 0 :(得分:2)

您可以添加'limit'=&gt; 1到你的参数数组只返回一个注释。

或者,您可以使用Containable行为来限制执行查找时返回的注释数,而不是定义另一个关系。

$this->Post->find('all',array(
                     'contain' => array(
                          'Comment' => array(
                              'order' => 'Comment.created DESC',
                              'limit' => 1
                          )
                      )
                  );

如果您想在不定义关系的情况下过滤任何相关集合(按作者或在日期范围内),这非常有用。

确保将Containable行为添加到您引用的任何模型中。

答案 1 :(得分:0)

删除要使用的重复项:查找所有查询中的GROUP BY。我相信Cake有'group'=&gt;选项也是。