I'm trying to select database rows in CakePHP based on the MAX() value of a field from another table. Here is the SQL I am trying to execute:
SELECT `questions`.* FROM `tests`,`questions` GROUP BY `questions`.`id` HAVING `questions`.`test_id` = MAX(`tests`.`id`);
(Or something equivalent. Basically, I'm trying to just grab all of the rows from the questions table where test_id equals the highest ID value in the tests table.)
The closest thing I have been able to do in CakePHP using find() is something that runs two queries:
$current_test = $this->find('first',array('fields'=>array('MAX(Test.id) as current_test')));
$questions = $this->find('all',array(
'conditions'=>array('Question.test_id'=>$current_test[0]['current_test'])
));
It gets me the results I need, but it seems unnecessary. Is there any way in CakePHP to put this into a single query?
JOIN. That seems unnecessary.