CakePHP嵌套两个选择查询

时间:2012-08-04 18:17:41

标签: php mysql cakephp

我在cakePHP中有两个表。

competencies
------------
id
name

competenceRatings
-----------------
id
competence_id
user_id
rating

我需要一种以蛋糕方式编写以下查询的方法:

SELECT * FROM能力WHERE id NOT IN(SELECT compe_id FROM compe_ratings WHERE employee_id = $ userId)

有人请帮帮我!!

在使用这个子查询方法之前我做了什么:

我尝试了能力 - > hasMany-> compeRatings,compeRatings-> belongsTo->能力关系。

$competencies = $this->Competence->CompetenceRating->find('all',array('CompetenceRating.user_id' => $userId,'CompetenceRating.competence_id !=' => 'Competence.id'));

我希望能够获得用户未在compeRatings表中进行任何评级的能力名称。即,我需要来自能力表的名单列表,其中comptenceRatings表中没有条目(对于给定的user_id)。

修改

我也试过表加入:

$options['joins'] = array(
            array(
                'table' => 'competence_ratings',
                'alias' => 'CompetenceRating',
                'type' => 'LEFT OUTER',
                'conditions' => array(
                    'Competence.id = CompetenceRating.competence_id'
                )
            )
        );
$options['conditions'] = array( 'CompetenceRating.employee_id' => $employee['Employee']['id'] );

$competencies = $this->Competence->find('all',$options);

1 个答案:

答案 0 :(得分:2)

您可能必须使用子查询():

$subqueryOptions = array('fields' => array('competence_id'), 'conditions' => array('employee_id'=>$user_id));
$subquery = $this->Competence->CompetenceRating->subquery('all', $subqueryOptions);

$res = $this->Competence->CompetenceRating->find('all', array(
    'conditions' => array('id NOT IN '. $subquery)
));

子查询的来源在这里: https://github.com/dereuromark/tools/blob/2.0/Lib/MyModel.php#L405 你需要把它放在你的AppModel.php

但我认为子查询不是必需的。你可以用它做一个简单的查询:

$this->Competence->CompetenceRating->find('all', array(
    'group' => 'competence_id', 
    'conditions' => array('NOT' => 'employee_id'=>$user_id)),
    'contain' => array('Competence')
));

如果您将递归设置为-1,请不要忘记通过“contains”包含Competence。