2011-07-10 36 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']; 

希望這有助於