cakePHP HABTM找到条件

时间:2011-08-08 22:18:29

标签: cakephp

我设置了以下关系:

师:

    var $hasAndBelongsToMany = array(
    'Classroom' => array(
        'className' => 'Classroom',
        'joinTable' => 'classrooms_teachers',
        'foreignKey' => 'teacher_id',
        'associationForeignKey' => 'classroom_id',
        'unique' => true,
    )
);

课堂:

    var $hasAndBelongsToMany = array(
    'Teacher' => array(
        'className' => 'Teacher',
        'joinTable' => 'classrooms_teachers',
        'foreignKey' => 'classroom_id',
        'associationForeignKey' => 'teacher_id',
        'unique' => true,
    )
);  

var $hasMany = array(
'Student' => array(
        'className' => 'Student',
        'foreignKey' => 'classroom_id',
        'dependent' => false,
    ),
);

学生:

    var $belongsTo = array(
    'Classroom' => array(
        'className' => 'Classroom',
        'foreignKey' => 'classroom_id',
    ),
  );

我正在尝试为教师创建一个仪表板,显示所有通过教室与教师相关的学生。

我正在使用以下查找操作:

    $students = $this->Teacher->Classroom->find('all', array(
                                        'conditions' => array('Classroom.teacher_id' => $this->Access->getTeacherId()),
    ));

但是,我收到错误:Unknown column 'Classroom.teacher_id' in 'where clause'

我必须做错事,因为蛋糕没有做关联。

有什么想法吗?

3 个答案:

答案 0 :(得分:3)

这是实现这一目标的正确方法:

        $this->Teacher->bindModel(array('hasOne' => array('ClassroomsTeachers')));

    $students = $this->Teacher->find('all', array(
                                        'conditions' => array('ClassroomsTeachers.teacher_id' => $this->Access->getTeacherId()),
                                        'recursive' => 2
    ));

我希望它有所帮助!

答案 1 :(得分:1)

这不是最好的方式。只需使用containsable和find('first'),你就不需要找到所有:

$students = $this->Teacher->find('first', array(
       'conditions' => array('Teacher.id' => $this->Access->getTeacherId()),
       'contain' => array('Classroom'=>array('Student'))
));

这将为您提供与教师相关的所有教室以及这些教室中的所有学生。

答案 2 :(得分:0)

我做了一个解决HABTM问题的行为。

在这里发表我的回答:

HABTM Find with CakePHP 2.0