1

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?

ronalchn
  • 12,225
  • 10
  • 51
  • 61
mirage
  • 111
  • 1
  • 11

2 Answers2

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

Joni
  • 108,737
  • 14
  • 143
  • 193
  • You could write that more neatly with: `$membership = $this->Membership->find('all', array('contain'=>array('TeacherCourse.Teacher'));` – petervaz Sep 20 '12 at 16:33
  • Now I feel stupid I didnt find this myself. Thank you very much for telling me about those two options, ofcourse I decided to go with Containable behaviour. – mirage Sep 20 '12 at 16:39
  • One more thing, when i did this, number of mysql queries grew a lot. For every teacher in the membership list it did this: "SELECT `Teacher`.`id`, `Teacher`.`first_name`, `Teacher`.`last_name`, `Teacher`.`additional_description`, `Teacher`.`created`, (CONCAT(`Teacher`.`first_name`, ' ' ,`Teacher`.`last_name`)) AS `Teacher__full_name` FROM `glasbena`.`teachers` AS `Teacher` WHERE `Teacher`.`id` = 5" I sopouse this is normal, because for every membership from the list it has to get a proper teacher? – mirage Sep 20 '12 at 17:00
  • Yes. that is the usual behavior of Containable. – petervaz Sep 20 '12 at 17:42
  • This is known as a "n plus one problem." If the number of queries (and the amount of data returned from the db) becomes a problem there are a few things you can do... – Joni Sep 20 '12 at 20:43
0

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.