Cakephp最小值查询

时间:2011-07-10 13:47:16

标签: php cakephp

我在Cakephp中有这个问题,我可以从得分字段中检索最小值,但我似乎无法使用group aswell获取同一行的id。以下是我的代码。我做错了什么?

function index() {
    $this->Leaderboard->recursive = 0;
    $this->set('leaderboards', $this->paginate());

    $min = $this->Leaderboard->find('all',
    array(
        'fields' => array('MIN(Leaderboard.score) as min_score')    
        ));
        $minimum = $min[0][0]['min_score'];
        pr($min);   
        echo $minimum;
    if (!empty($this->data)) {
        $this->Leaderboard->create();
        if($this->data['Leaderboard']['score'] > $minimum){
        if ($this->Leaderboard->save($this->data)) {
            $this->Session->setFlash(__('The leaderboard has been saved', true));
            $this->Leaderboard->delete($min[0]['Leaderboard']['id']);
        } else {
            $this->Session->setFlash(__('The leaderboard could not be saved. Please, try again.', true));
        }
        } else {
            $this->Session->setFlash(__('Score not high enough for leaderboard',true));
        }
    }
    $users = $this->Leaderboard->User->find('list');
    $trips = $this->Leaderboard->Trip->find('list');
    $this->set(compact('users', 'trips'));
}

2 个答案:

答案 0 :(得分:2)

U必须使用子查询来获取与最小值相同的行的ID ..

查询会是这样的

SELECT id 
FROm Leaderboard 
WHERE score IN (
    SELECT MIN(score) 
    FROM Leaderboard
        );

如何在cakephp中使用子查询,请查看http://book.cakephp.org/view/1030/Complex-Find-Conditions

我完成了同样的任务,但以其他方式

$minimum = $this->Leaderboard->find('first',array(
    'fields'=>array('MIN(score) as MinimumScore')));

$data = $this->Leaderboard->find('first',array(
    'fields'=>array('id'),
    'conditions'=>array('score'=>$minimum[0]['MinimumScore'])));

现在你可以访问id

 $id = $data['Leaderboard']['id'];

希望这个帮助

答案 1 :(得分:0)

你可以尝试这样的事情。 **免责声明 - 我没有测试这段代码,但是它太长了,不适合评论,所以......

$min = $this->Leaderboard->find('first', array(
        'fields' => array('Leaderboard.id', 'Leaderboard.score'),
        'order' => 'Leaderboard.score ASC'
        )
);