查找hasMany关系的条件'NOT EXISTS'

时间:2011-09-08 00:01:38

标签: cakephp

这个问题类似于Find conditions like 'NOT EXISTS',只是它正在使用hasMany关系。

表格是:

问题 id bigint ...

答案 id bigint question_id bigint ...

关系是问题,有很多答案。

查询是查找没有答案的问题ID。

SQL可能看起来像

select id from questions where not exists 
    (select * from answers where answers.question_id = questions.id)

快速的方法是使用语句运行query(),但我想知道是否有CakePHP方式。

我想避免使用NOT IN方案,因为这可能导致数据库的两次点击;一个用于获得有答案的问题的所有问题ID,第二个用于获得没有答案的问题的所有问题ID。

另一种方法可能是将conditions数组中的整个where子句作为单个条目。我只是不确定这是不是最好的做法。

2 个答案:

答案 0 :(得分:8)

无需更改数据库,我最终使用以下查询:

$questions = $this->Questions->find('all', array(
    'fields' => array('id'),
    'conditions' => array('not exists '.
        '(select id from answers '.
        'where answers.question_id = '.
        'Question.id)'
     )
));

答案 1 :(得分:3)

执行此操作的最佳方法是在posts表中包含count字段。 Cake具有称为计数器缓存的内置功能。

class Post extends AppModel
{
    var $name = "Post";
    var $hasMany = array('Answer'=>array('counterCache'=>true));
}

您需要将answer_count添加到帖子表中。在添加和删除相关记录时,此列将自动更新。

然后您的查询是一个简单的查找:

$this->Post->find('all', array('conditions' => array('answer_count' => 0)));

此处的文档: http://book.cakephp.org/view/1033/counterCache-Cache-your-count

相关问题