1
votes

I have two tables in cakePHP.

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

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

I need a way to write the following query in the cake way:

SELECT * FROM competencies WHERE id NOT IN (SELECT competence_id FROM competence_ratings WHERE employee_id = $userId)

Someone please help me!!

What i did before going to this subquery method:

I tried competencies->hasMany->competenceRatings, competenceRatings->belongsTo->competencies relations.

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

I want to be able to get the names of competencies for which a user have NOT made any ratings into competenceRatings table. i.e., I need list of names from competencies table for which there are no entries in comptenceRatings table(for given user_id).

EDIT

I tried table join also:

$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
what did you try so far? - mark
I was talking about actual code. instead of just posting the expected outcome you should also post what you coded so far. you can just edit and complete your question above. - mark
you have again ask same question befor 2 or 3 hrs you ask "cakePHP table joining two tables issue" this question - Abid Hussain
@mark i have edited the code. Please have a look. - Ivin Jose

1 Answers

2
votes

you would probably have to use a subquery():

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

the source for subquery is here: https://github.com/dereuromark/tools/blob/2.0/Lib/MyModel.php#L405 you need to put this in your AppModel.php

BUT I think the subquery is not necessary. You can probably make a single and easy query out of it:

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

dont forget to include Competence via "contain" if you have recursive set to -1.