cakePHP table joining two tables issue

陌路散爱 提交于 2019-12-11 17:52:03

问题


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

回答1:


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


来源:https://stackoverflow.com/questions/11809246/cakephp-table-joining-two-tables-issue

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!