2011-04-22 82 views
2

这很简单,但我想我以前从来没碰过它。我有一个Page型号,即hasMany Comment。我想抽出至少有1条评论的所有网页,但是不要删除任何网页。当我看着它时,我意识到我不知道该怎么做。我想我可以使用ad hoc连接,但我宁愿使用Containable,如果可能的话。我试过在Comment条件下测试not null以及其他一些不太可能工作的东西,但看起来这应该是可能的。只能检索至少有一个关联的记录

当然,我现在得到的是所有页面,其中一些页面记录有一个空的Comment成员。如果我可以这么做,不妨绕过所有额外的东西来跳过。

find电话:

$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, 
     ), 
    ) 
    ); 

感谢。

回答

3

你比特设几种方法可供其他加入:

  1. 进行非标准化数据集,并添加has_comment标志到您的网页表格。根据您的条件添加'Page.has_comment' => 1
  2. 使用DISTINCT page_id针对评论运行您的查询。

    $comments = $this->Folder->Page->Comment->find('all', array(
        'conditions' => array('DISTINCT Comment.page_id' 
        'contain' => array(
         'Page' => array(
           'Folder' 
         ) 
        ) 
    ); 
    
  3. 首先从注释表中获取一组不同的页面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(
         ... 
        ) 
    ); 
    
+0

好建议,我有第三个选项去。 – 472084 2012-06-29 14:31:12

相关问题