0

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?

1
  • Personally I think the CakePHP code is better than your MySQL query. In which you're selecting two tables without a JOIN. That seems unnecessary. Commented May 17, 2011 at 21:19

1 Answer 1

2

If you're model relationships are setup properly and I understand your database, the following should work (assuming this code is being written INSIDE your Test Model. If it's outside your Test Model (i.e. in a Controller), you'll need to use $this->Test->find.

$test = $this->find( 'first', array(
    'order'     => 'Test.id desc',
    'recursive' => 1,
));

Which should return something like:

$test = array(
    [Test] => array(
        'id'  => X,
        'etc' => '...'
    ),

    [Questions] => array( 
        [0] => array( 'test_id' => X, 'question_id' => 1  ),
        [1] => array( 'test_id' => X, 'question_id' => 7  ),
        [2] => array( 'test_id' => X, 'question_id' => 10 ),
    ),
);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.