Attempts belong to Users (Users have many Attempts).
In User.php (model)
public $hasMany = array (
'Attempt' => array(
'className' => 'Attempt',
'order' => 'modified DESC'
),
);
In Attempt.php (model)
public $belongsTo = array (
'Test' => array ('className' => 'Test', 'foreignKey'=>'test_id', 'order' => 'Test.created DESC'),
'User' => array ('className' => 'User', 'order' => 'User.created DESC')
);
In a controller, I construct this query...
$joins = array(
array(
'table'=>'attempts',
'alias'=>'Attempt',
'type'=>'LEFT',
'conditions'=>array("Attempt.user_id = User.id AND Attempt.test_id != {$practice_test_id}")
)
);
$conditions[] = array('Resume.has_file = 1');
$search_options = array( 'conditions'=>$conditions,
//'joins' => $joins, //<--I'M FORCED TO USER THIS TO GET THIS TO WORK
'contain' => array('Resume', 'Attempt', 'Tag'),
'order' => array('Attempt.score'=> 'DESC'),
'group' => 'User.id'
);
$paginator_settings = $search_options;
$paginator_settings['limit'] = 25;
$this->Paginator->settings = $paginator_settings;
$resume_display_array = $this->Paginator->paginate('User');
(It looks a bit strange here because I stripped out a lot of distracting logic that happens in between the construction of this query. Most of these conditions are built dynamically based on user input.)
When I leave out the $search_options['joins]
this does not work. I get the following error:
Error: SQLSTATE[42S22]: Column not found: 1054 Unknown column 'Attempt.score' in 'order clause'
The SQL dump looks something like this:
SELECT `User`.`id`
FROM `users` AS `User`
LEFT JOIN `resumes` AS `Resume` ON (`Resume`.`user_id` = `User`.`id`)
WHERE `User`.`id` IN (
SELECT `User1`.`id` FROM `users` AS User1
LEFT JOIN `tags_users` AS TagUser ON (`User1`.`id`= `TagUser`.`user_id`)
LEFT JOIN `tags` AS Tag ON (`TagUser`.`tag_id`= `Tag`.`id`)
WHERE `Tag`.`id` = (2) ) AND `Resume`.`has_file` = 1 GROUP BY `User`.`id`
ORDER BY `Attempt`.`score` DESC
LIMIT 25
Why isn't the Attempt model getting included automatically due to its hasMany relationship with User?