Even after digging through "Specifying order parameter through a belongsTo table in CakePHP" I can't seem to order entries in a table that belong to entities stored in another table.
Essentially, I've got a Tutorial model which hasMany Exercise. Each Exercise belongsTo Tutorial (of course) and also belongsTo an ExerciseCategory. When I set recursive = 2 and find a given tutorial I'd like to get back a list of Exercise rows, ordered first by ExerciseCategory.title and then by Exercise.sequence_number.
So here's my question: My great/hackish idea was to order the results of the query based on the raw exercise_category_id, like so:
class Exercise extends AppModel {
public $belongsTo = array(
'Tutorial',
'ExerciseCategory'
);
public $order = array( 'exercise_category_id' => 'ASC', // <=========
'sequence_number' => 'ASC'); // <=========
I don't understand why this doesn't work, either. It produces the following SQL query:
SELECT `Exercise`.`id`, `Exercise`.`exercise_category_id`,
`Exercise`.`tutorial_id`, `Exercise`.`sequence_number`,
`Exercise`.`body`
FROM `Tutorial`.`exercises` AS `Exercise`
WHERE `Exercise`.`tutorial_id` = (1)
Based on the CakePHP documentation it seems like there ought to be an ORDER BY clause in the query, but there isn't.
What do I need to do to get the Exercise rows ordered by the exercise_category_id number so that they'll be grouped up the way I want?
"Specifying order parameter through a belongsTo table in CakePHP" suggests setting up the Exercise.php model file like this:
class Exercise extends AppModel {
public $belongsTo = array(
'Tutorial',
'ExerciseCategory' =>
array(
'order' => array('ExerciseCategory.title'=>'asc', 'Exercise.sequence_number' => 'asc'))
);
but that produces an erroneous SQL query:
SELECT `ExerciseCategory`.`id`, `ExerciseCategory`.`explanation`,
`ExerciseCategory`.`title`
FROM `Tutorial`.`exercise_categories` AS `ExerciseCategory`
WHERE `ExerciseCategory`.`id` = 2
ORDER BY `ExerciseCategory`.`title` asc, `Exercise`.`sequence_number` asc
The problem (as CakePHP helpfully points out) is that CakePHP doesn't include the Exercises table in the query.
EDIT: Here's the code to actually generate the various queries:
$this->Tutorial->recursive = 2;
$this->Tutorial->Chapter->unbindModel(array('hasMany' => array('Tutorial')));
$this->Tutorial->Exercise->unbindModel(array('belongsTo' => array('Tutorial')));
$this->Tutorial->Section->unbindModel(array('belongsTo' => array('Tutorial')));
$tut = $this->Tutorial->findById($id);