我说模型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>
答案 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;选项也是。