Ivin
Ivin

Reputation: 4815

cakePHP table joining two tables issue

Im new to cakePHP and the whole table relations concept is very confusing!

I have 2 tables, competencies and competenceRatings. competencies stores a list of names with ids.

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

And users can select various competencies from this table and rate them and their ratings are stored into competenceRatings table.

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

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).

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

But no use!

Does this result require any other relations? Or can i just join tables using joins condition in find query?

Thanks.

EDIT

This method worked:

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

Upvotes: 0

Views: 5733

Answers (1)

Abid Hussain
Abid Hussain

Reputation: 7762

Try this

Joining tables

$data = $this->Competence->find('all', array('joins' => array(
    array(
        'table' => 'competenceRatings',
        'alias' => 'CompetenceRating',
        'type' => 'inner',
        'foreignKey' => false,
        'conditions'=> array('CompetenceRating.competencie_id = Competence.id')
    ),
    array(
        'table' => 'competencies',
        'alias' => 'Competence',
        'type' => 'inner',
        'foreignKey' => false,
        'conditions'=> array(
            'Competence.id = MarkersTag.tag_id',
            'Competence.user_id' => $user_id
        )
    )
)));

Upvotes: 2

Related Questions