I'm trying to use Containable to return a model with several of its associated models (and those arrays of data). The models deal with test results. Here are the models:
Models:
Question : has and belongs to many Category
Category : has and belongs to many Question
Attempt : has many AttemptedQuestions
AttemptedQuestion : belongs to Question
I want to return an Attempt with all of it's AttemptedQuestions and their corresponding Quesions + Category
So basically, the relationships map like this:
Attempt => AttemptedQuestion(s) => Question => Category
I suspect that because of the HABTM relationship, Cake would prefer to return:
Attempt => AttemptedQuestion(s) => array( Question, Category ) <--Categories are not contained within the Question array, but rather they are sisters. This is fine as well.
At the moment I am unable to get Category to show up at all. Here's what I'm doing inside a controller (this does NOT result in the Categories appearing in results):
$this->Attempt->contain(array('AttemptedQuestion' => array('Question'=>'Category')));
$attempt_to_be_graded = $this->Attempt->findById( $attempt_id );
What am I doing wrong?
Update Here's a revision based on the answer from @nunser. This also does not work.
$this->Attempt->contain(array('AttemptedQuestion' => array('Question'=>array('Question'=>array('Category') ))));
$attempt_to_be_graded = $this->Attempt->findById($attempt_id );
This is what the data returned looks like:
array(
'Attempt' => array(
'id' => '39',
...
),
'AttemptedQuestion' => array(
(int) 0 => array(
'id' => '189',
...,
'Question' => array(
'id' => '165',
...
)
),
(int) 1 => array(
'id' => '188',
...,
'Question' => array(
'id' => '164',
...
)
)
)
)
Update 2
I'm still struggling with this, but I think my associations have to be correct because the following returns a list of all my Categories just as expected:
$categories = $this->Attempt->AttemptedQuestion->Question->Category->find('all');
Update 3
I've narrowed down the scope of this problem by testing the results of $this->Question->find('first') from various points throughout the code. It appears that the results are expected UNTIL after this: $test = $this->Test->findById($test_id);.
Here is the code which demonstrates:
$this->loadModel('Question');
$test = $this->Question->find('first');
debug($test);
//THESE RESULTS INCLUDE Category DATE
$test = $this->Test->findById($test_id);
$this->loadModel('Question');
$test = $this->Question->find('first');
debug($test);
exit;
//THESE RESULTS DO NOT INCLUDE Category DATE
So for reasons I completely do not understand, the intervening Test->find() seems to prevent the Category data from appearing afterwards. Weird, huh?