为了解释我遇到的问题,我会举个例子。假设我正在建立一个系统,学生可以注册一个或多个课后课程,但学校官员必须批准注册才能使其有效。所以我有这些模型:
现在,假设我想看一张九年级学生所有未经批准的注册名单。这很简单:
$this->request->data = $this->Student->CoursesStudent->find('all', array(
'conditions' => array(
'CoursesStudent.is_approved' => null,
'Student.grade' => 9
)
));我正在苦苦挣扎的是,我也在调取老师的数据(不仅仅是他们的身份证)。我试过这个:
$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
)
)
)谢谢!
发布于 2012-12-11 21:23:00
在使用$recursive之前,必须将contain()设置为-1。
此外,确保您的模型被设置为使用可包含的行为。在这种情况下,因为'Course‘也包含了一些东西,所以它也需要使用可控制的行为。
(您可以考虑将下面的$actsAs设置在您的AppModel中,以便使每个模型都可以使用。)
//in your CoursesStudent model (and in your Course model)
public $actsAs = array('Containable');下面是您的发现,但首先设置递归:
$this->Student->CoursesStudent->recursive = -1;
$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'
)
));https://stackoverflow.com/questions/13826474
复制相似问题