Nick
Nick

Reputation: 8319

CakePHP HABTM recursive issue

To explain the issue I'm having, I'll use an example. Let's say that I'm building a system where students can sign up for an afterschool class, but an administrator has to approve the sign-up in order for it to be valid. So I have these models:

Now let's say I want to see a list of all of the unapproved sign-ups that are for ninth-graders. I want the list to include the calendar date, the student's name, and the teacher's name. I would do something like this:

$this->request->data = $this->Student->CalendarsStudent->find('all', array(
    'conditions' => array(
        'CalendarsStudent.is_approved' => null,
        'Student.grade' => 9
    )
));

The problem with the above code is that the returned array is missing the teacher's name:

Array
(
    [0] => Array
        (
            [CalendarsStudent] => Array
                (
                    [id] => 1274
                    [calendar_id] => 200
                    [student_id] => 872
                    [is_approved] => 
                )

            [Calendar] => Array
                (
                    [id] => 200
                    [date] => 2012-12-17
                    [teacher_id] => 1
                    [total_slots] => 15
                )

            [Student] => Array
                (
                    [id] => 872
                    [teacher_id] => 1
                    [first_name] => Billy
                    [last_name] => Smith
                    [grade] => 9
                )

        )

)

If I add 'recursive' => 2 to the find parameters, I get way too much information. $this->request->data[0]['Calendar'] will have [Teacher], which is what I want, but it will also have [Student], which I don't want. Also, $this->request->data[0]['Student'] will have subarrays that I don't want. It seems like Containable would fix this, but I can't get that to work either.

Any ideas?

Upvotes: 0

Views: 559

Answers (1)

Dave
Dave

Reputation: 29141

Use CakePHP's [Containable Behavior]. It's amazing - easy to use and will return whatever you want it to.

Side note: If you're using "recursive" as anything other than -1 for ANYTHING, it should be a red flag. Containable is the absolute way to go as it lets you specify easily and exactly what data you want returned. Recursive will often cause memory issues and or other badness.

Best practice IMO: set $recursive = -1; in your AppModel.php and never set it to anything else...ever.

Upvotes: 2

Related Questions