这个问题类似于'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)
Run Code Online (Sandbox Code Playgroud)
快速的方法是使用语句运行query(),但我想知道是否有CakePHP方式.
我想避免使用NOT IN方案,因为这可能导致数据库的两次点击; 一个用于获得有问题答案的所有问题ID,第二个用于获取没有答案的问题的所有问题ID.
另一种方法可能是将条件数组中的整个where子句作为单个条目.我只是不确定这是不是最好的做法.
无需更改数据库,我最终使用以下查询:
$questions = $this->Questions->find('all', array(
'fields' => array('id'),
'conditions' => array('not exists '.
'(select id from answers '.
'where answers.question_id = '.
'Question.id)'
)
));
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4748 次 |
| 最近记录: |