cakePHP model associations (retrieving data deeper)

我怕爱的太早我们不能终老 提交于 2019-12-08 05:00:43

问题


I tried to find this everywhere but I cant. Here is my problem:

Lets say I have models associated like this:

  1. Student (has many Memberships)
  2. Membership (belongs to Student and TeacherCourse)
  3. TeacherCourse (belongs to Teacher and Course)
  4. Teacher (has many TeacherCourses)
  5. Course (has many TeacherCourses)

When I use membershipsController to send all membership to the view, I get only for example $membership['Membership']['id'] or $membership['TeacherCourse']['id'] BUT NOT $membership['TeacherCourse']['Teacher']['id']...

Which means I get info on Memberships and TeacherCourse because they are directly associated. My question is how can I also get info about Teachers or Courses directly?


回答1:


You could increase the model's recursion level to obtain deeper associations (set $this->Membership->recursive to 2 or 3), but in general it's better to use the Containable behavior so you can choose which associations you want to retrieve. For example this would return memberships with associated TeacherCourse and Teacher models:

$membership = $this->Membership->find('all', array(
    'contain'=>array(
        'TeacherCourse'=>array(
            'Teacher'=>array()
        ),
    ));

See also the full documentation of the Containable behavior at http://book.cakephp.org/2.0/en/core-libraries/behaviors/containable.html




回答2:


Scratching my head for a few minutes on this one when I realised you need to add the following to the Model first:

public $actsAs = array('Containable');

Just adding the contain array in the controller may not return the variables you're looking for in the view without the above.



来源:https://stackoverflow.com/questions/12515706/cakephp-model-associations-retrieving-data-deeper

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!