Tuesday, March 27, 2012

multi-level Model associations behavior

I am building an eLearning site in CakePHP that has models: Course,
Test, Question, Answer, and others.

Here are my associations:

Course hasMany Test
Test belongsTo Course
Question belongsTo Test
Question hasMany Answer
Answer belongsTo Question

This model association works fine in most circumstances. For example,
the baked CRUD actions for Course know that there are Test(s) that
belong to it, Questions know they have associated Answer(s), etc...

But I am trying to write a Test management tool that operates within
the TestsController and level of association ends at Question. There
are no answers. In other words, the view I'm working on has this by
default from the baked TestsController:

Array
(
[Test] => Array
(
[id] => 1
[name] => Test 1
[course_id] => 1
[time_limit] => 30
[max_questions] => 20
[randomize_order] => 1
[num_questions] => 2
)

[Course] => Array
(
[id] => 1
[course_identifier] => TLE1001
[title] => Child Development I
[description] =>
)

[Question] => Array
(
[0] => Array
(
[id] => 1
[text] => What is your name?
[test_id] => 1
[order] => 0
)

[1] => Array
(
[id] => 2
[text] => What is my name?
[test_id] => 1
[order] => 0
)

)

)

As you can see, the $test array in my view stops at Question, and
doesn't pull the associated Answer(s) for the Question(s).

I fixed this problem by changing the bottom of my 'view' action in
TestsController:

$test = $this->Test->read(null, $id);
$test['Question'] = $this->Test->Question->find('all'); //I added this
line...
$this->set('test', $test);

I added the middle line so it literally replaces all the contents of
$test['Question'] manually before it sets the $test array for the view
to use.

That works for what I have to accomplish, but it seems ugly to me. Is
there a better way to do this? Does CakePHP only build associated
data array's for model association up to a certain level then stop?

P.S. I tried to add:

var $uses = array('Test', 'Question', 'Answer');

...to the top of my TestsController but it did not fix the problem and
seemed to have no effect.


--
Our newest site for the community: CakePHP Video Tutorials http://tv.cakephp.org
Check out the new CakePHP Questions site http://ask.cakephp.org and help others with their CakePHP related questions.


To unsubscribe from this group, send email to
cake-php+unsubscribe@googlegroups.com For more options, visit this group at http://groups.google.com/group/cake-php

No comments: