开发者

Cakephp Minimum value query

I have this issue with Cakephp where I can retrieve min value from score field but I cannot seem to get id for the same row using group aswell. Below is my code. What am I doing wrong?

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->Leader开发者_StackOverflow社区board->User->find('list');
    $trips = $this->Leaderboard->Trip->find('list');
    $this->set(compact('users', 'trips'));
}


U have to use sub-query for getting id for the same row as that of minimum one ..

Query would something like this

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

and how to use sub-queries in cakephp take a look at http://book.cakephp.org/view/1030/Complex-Find-Conditions

I have done the same task but in other way

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

and now u can access id as

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

Hope this help


You can try something like this. ** Disclaimer -- I didn't test this code, but it's too long to fit in a comment, so...

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜