为了解释我遇到的问题,我将使用一个示例。假设我正在构建一个系统,学生可以在其中注册一个或多个课后课程,但学校官员必须批准注册才能使其有效。所以我有这些模型:
- 课程(属于“老师”,hasAndBelongsToMany“学生”)
- 学生(hasAndBelongsToMany“课程”)
- 老师(有很多“课程”)
现在假设我想查看所有针对九年级学生的未批准注册的列表。这很容易:
$this->request->data = $this->Student->CoursesStudent->find('all', array(
'conditions' => array(
'CoursesStudent.is_approved' => null,
'Student.grade' => 9
)
));
我正在努力解决的问题是同时提取教师的数据(不仅仅是他们的 ID)。我试过这个:
$this->request->data = $this->Student->CoursesStudent->find('all', array(
'conditions' => array(
'CoursesStudent.is_approved' => null,
'Student.grade' => 9
),
'contain' => array(
'CoursesStudent',
'Course' => array(
'Teacher' => array(
'fields' => array(
'Teacher.id',
'Teacher.name'
)
)
),
'Student'
)
));
但它对返回的数组没有任何影响。为了方便您将其放入现有的 CakePHP 项目中进行使用,这里是数据库模式和数据,这里是您可以粘贴到现有 CakePHP 项目的随机操作中的内容。这就是我想要得到的(注意老师的数据在那里):
Array
(
[0] => Array
(
[CoursesStudent] => Array
(
[id] => 1
[course_id] => 1
[student_id] => 1
[is_approved] =>
[created] => 2012-12-11 00:00:00
[modified] => 2012-12-11 00:00:00
)
[Course] => Array
(
[id] => 1
[teacher_id] => 1
[title] => Introduction to Improvisation
[start_date] => 2012-12-17
[end_date] => 2012-12-21
[created] => 2012-12-11 00:00:00
[modified] => 2012-12-11 00:00:00
[Teacher] => Array
(
[id] => 1
[first_name] => John
[last_name] => Doe
[created] => 2012-12-11 00:00:00
[modified] => 2012-12-11 00:00:00
)
)
[Student] => Array
(
[id] => 1
[first_name] => Bill
[last_name] => Brown
[grade] => 9
[created] => 2012-12-11 00:00:00
[modified] => 2012-12-11 00:00:00
)
)
)
谢谢!