HABTM错误不是唯一的表别名

时间:2014-09-18 14:23:57

标签: cakephp

我正在尝试将HABTM模型与连接相关联,但我一直收到此错误。 Tutor有一个独特的表格,所以我不确定为什么会出现这个错误? 这是具有关系的控制器和模型

错误:SQLSTATE [42000]:语法错误或访问冲突:1066不唯一的表/别名:' Tutor'

class Subject extends AppModel {
public $hasAndBelongsToMany = array(

    'Tutor' => array(
        'className' => 'Tutor',
        'joinTable' => 'tutors_subjects',
        'foreignKey' => 'subject_id',
        'associationForeignKey' => 'tutor_id',
        'unique' => 'keepExisting',
        'conditions' => '',

    )
);

}

class Tutor extends AppModel {
    ..

    public $hasAndBelongsToMany = array(
        'Subject' => array(
            'className' => 'Subject',
            'joinTable' => 'tutors_subjects',
            'foreignKey' => 'tutor_id',
            'associationForeignKey' => 'subject_id',
            'unique' => 'keepExisting',
            'conditions' => '',

        ),

    );

class TutorsController extends AppController {

 public function tutordetails() {

     //    $tutor=$this->Tutor->find('all', array(  'conditions'=>array('Tutor.id'=> 1),'recursive' => -1 ) );
     //    $this->set( 'tutor',$tutor);
       //   debug($tutor);



            $options2['joins'] = array(
               array('table' => 'tutors_subjects',
                'alias' => 'TutorsSubject',
                'type' => 'LEFT',
                'conditions' => array(
                'Tutor.id = TutorsSubject.id',
                 )
                 ),

                array('table' => 'subjects',
                'alias' => 'Subject',
                'type' => 'LEFT',
                'conditions' => array(
                'TutorsSubject.subject_id=Subject.id',
                 )
                 ),

                 array( 'table' => 'tutors',
            'alias' => 'Tutor',
            'type' => 'LEFT',
            'conditions' => array(
            'TutorsSubject.tutor_id = Tutor.id',
        )

            ));





            $options2['fields'] = array('Subject.*','TutorsSubject.*','Tutor.*');



            $options2['conditions'] = array('Tutor.id'  => 2);
            $subject=$this->Tutor->find('first',$options2);


            $this->set('subject', $subject);
            debug($subject);

1 个答案:

答案 0 :(得分:1)

问题是你的JOIN子句中的这段代码:

 array( 'table' => 'tutors',
        'alias' => 'Tutor',
        'type' => 'LEFT',
        'conditions' => array(
        'TutorsSubject.tutor_id = Tutor.id',

您正在尝试自我加入并使用相同的别名的Tutors模型上执行查找。

试试这个:

 array( 'table' => 'tutors',
        'alias' => 'TutorOther',
        'type' => 'LEFT',
        'conditions' => array(
        'TutorsSubject.tutor_id = TutorOther.id',