【问题标题】:Finding based on MySQL function in CakePHPCakePHP中基于MySQL函数的查找
【发布时间】:2011-05-17 21:16:02
【问题描述】:

我正在尝试根据另一个表中字段的 MAX() 值在 CakePHP 中选择数据库行。这是我要执行的 SQL:

SELECT `questions`.* FROM `tests`,`questions` GROUP BY `questions`.`id` HAVING  `questions`.`test_id` = MAX(`tests`.`id`);

(或等效的东西。基本上,我试图从问题表中获取所有行,其中 test_id 等于测试表中的最高 ID 值。)

我在 CakePHP 中使用 find() 能做的最接近的事情是运行两个查询:

$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'])
));

它得到了我需要的结果,但似乎没有必要。 CakePHP 有什么方法可以将其放入单个查询中?

【问题讨论】:

  • 我个人认为 CakePHP 代码比你的 MySQL 查询要好。您在其中选择了两个没有JOIN 的表。这似乎不必要

标签: mysql cakephp


【解决方案1】:

如果您的模型关系设置正确并且我了解您的数据库,则以下内容应该有效(假设此代码是在您的测试模型内部编写的。如果它在您的测试模型之外(即在控制器中),您将需要使用$this->Test->find。

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

应该返回如下内容:

$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 ),
    ),
);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-10-13
    • 1970-01-01
    • 2010-11-27
    • 1970-01-01
    • 2015-07-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多