2011-07-10 38 views
0

我有CakePHP的这个问题,我可以从分数字段检索最小值,但我似乎无法获得使用组的同一行的id。以下是我的代码。我究竟做错了什么?Cakephp最小值查询

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')); 
} 
+0

难道你不喜欢它,当“快速发展框架”让生活难度比它应该是什么? –

+0

是否有你不能这样做的理由:'fields'=> array('Leaderboard.id','MIN(Leaderboard.score)as min_score')? – Dave

回答

0

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

$min = $this->Leaderboard->find('first', array(
     'fields' => array('Leaderboard.id', 'Leaderboard.score'), 
     'order' => 'Leaderboard.score ASC' 
     ) 
); 
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']; 

希望这有助于