这非常简单,但我想我以前从未遇到过它。我有一个 Page
模型,hasMany Comment
。我想提取所有至少有 1 条评论的页面,但删除没有评论的页面。当我看到它时,我意识到我不知道该怎么做。我想我可以使用临时连接,但如果可能的话,我宁愿使用 Containable。我尝试过在 Comment
条件下测试 not null
以及其他一两个不太可能起作用的东西,但看起来这应该是可能的。
当然,我现在得到的是所有页面,其中一些页面记录有一个空的 Comment
成员。如果我可以的话,请跳过所有额外的麻烦。
我的查找
调用:
$pages = $this->Folder->Page->find(
'all',
array(
'contain' => array(
'Comment' => array(
'order' => array( 'Comment.modified DESC' ),
),
'Folder' => array(
'fields' => array( 'Folder.id' ),
),
),
'conditions' => array(
'Folder.group_id' => $id,
),
)
);
谢谢。
最佳答案
除了临时联接之外,您还有多种可用方法:
- 对数据集进行非规范化并向页面表添加 has_comment 标志。将
'Page.has_comment' => 1
添加到您的条件中。 使用 DISTINCT page_id 对评论运行查询。
$comments = $this->Folder->Page->Comment->find('all', array( 'conditions' => array('DISTINCT Comment.page_id' 'contain' => array( 'Page' => array( 'Folder' ) ) );
首先从评论表中获取一组不同的页面 ID。
$page_ids = $this->Folder->Page->Comment->find('list', array( 'fields' => array('id', 'page_id'), 'conditions' => array('DISTINCT Comment.page_id'), ); $pages = $this->Folder->Page->find('all', array( 'conditions' => array('Page.id' => $page_ids), 'contain' => array( ... ) );
关于cakephp - 只检索至少有一个关联的记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5756065/