在此示例中,如何在模型中创建“分配到教师”关系?
assignments subjects teachers
--------- --------- ------
id id id
student_id subject_name teacher_name
subject_id teacher_id
我想要一个SQL查询,显示:assignment_id,student_id,subject_name,teacher_name。我使用“belongsTo”来创建“作业与作业”的关系,但我不确定如何创建“作业与教师”。
AssignmentsController.php
public function index() {
$this->set('assignments', $this->Assignment->find('all'));
}
--------------------------
Assignment.php
public $belongsTo = array(
'Subject'
);
我确实通过在控制器中向“find('all')”添加连接来实现此功能,但我想知道如何在模型中执行此操作。
AssignmentsController.php
//(working, but looking to solve this in models, not controller)
$this->set('assignments', $this->Assignment->find('all', array(
'joins' => array(
array(
'table' => 'subjects',
'alias' => 'Subject',
'type' => 'LEFT',
'conditions' => 'Assignment.subject_id = Subject.id'
),
array(
'table' => 'teachers',
'alias' => 'Teacher',
'type' => 'LEFT',
'conditions' => 'Subject.teacher_id = Teacher.id'
)
),
'fields' => array('*','Subject.subject_name', 'Teacher.teacher_name')
)));
答案 0 :(得分:1)
据我所知,assignments
与teachers
到subjects
有关,对吧?然后,在Subject
模型:
public $belongsTo = array('Teacher');
此外,在AppModel
上,使用Containable
行为:
public $actsAs = array('Containable');
现在,您可以通过以下方式查找assignment
:
$this->Assignment->find('all', array(
'fields' => array('id', 'student_id')
'contain' => array(
'Subject' => array(
'fields' => array('id', 'subject_name')
'Teacher' => array(
'fields' => array('id', 'teacher_name')
)
)
)
));
Containable
行为可让您通过相关模型进行深入搜索