gpt4 book ai didi

mysql - CakePHP中基于MySQL函数查找

转载 作者:行者123 更新时间:2023-11-29 09:09:34 25 4
gpt4 key购买 nike

我试图根据另一个表中字段的 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 有什么方法可以将其放入单个查询中吗?

最佳答案

如果您的模型关系设置正确并且我了解您的数据库,则以下内容应该有效(假设此代码是在您的测试模型内编写的。如果它在您的测试模型之外(即在 Controller 中),您将需要使用$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 ),
),
);

关于mysql - CakePHP中基于MySQL函数查找,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6037233/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com