2014-02-16 55 views
1

貢獻者有歌曲和歌曲有貢獻者。我希望能夠按貢獻者擁有的歌曲數量進行排序。CakePHP分頁 - 按虛擬字段排序

在我的控制器:

public $paginate = array(
    'fields' => array(
     'Contributor.id', 
     'Contributor.name', 
     'COUNT(DISTINCT ContributorsSong.song_id) AS Contributor__TotalSongs', 
    ), 

    'joins' => array(
     array(
      'alias' => 'ContributorsSong', 
      'table' => 'contributors_songs', 
      'type' => 'LEFT', 
      'conditions' => 'ContributorsSong.contributor_id = Contributor.id' 
     ), 
     array(
      'alias' => 'Song', 
      'table' => 'songs', 
      'type' => 'LEFT', 
      'conditions' => 'ContributorsSong.song_id = Song.id' 
     ) 
    ), 

    'group' => array('ContributorsSong.contributor_id') 

); 

而且在我的索引方法。

$this->Contributor->recursive = 0; 
    $this->Paginator->settings = $this->paginate; 
    $this->Contributor->virtualFields['TotalSongs'] = 0; 

    $items = $this->paginate(); 

    echo '<pre>';print_r($items);echo '</pre>'; 

我想通過歌曲數量通過使用虛擬字段進行排序,所以當我去

本地主機/網站/撰稿人/索引/排序:TotalSongs/

我得到這個錯誤:

Error: SQLSTATE[42S22]: Column not found: 1054 Unknown column '0' in 'order clause'

SQL Query: SELECT Contributor . id , Contributor . name , COUNT(DISTINCT ContributorsSong.song_id) AS Contributor__TotalSongs FROM db_songs2 . contributors AS Contributor LEFT JOIN db_songs2 . contributors_songs AS ContributorsSong ON (ContributorsSong . contributor_id = Contributor . id) LEFT JOIN db_songs2 . songs AS Song ON (ContributorsSong . song_id = Song . id) WHERE 1 = 1 GROUP BY ContributorsSong . contributor_id ORDER BY (0) desc LIMIT 18

我認爲TotalSongs會得到變成查詢Contributor__TotalSongs但它被變成。這裏發生了什麼?謝謝。

回答

1

我代替:

$this->Contributor->virtualFields['TotalSongs'] = 0; 

有:

$this->Contributor->virtualFields['TotalSongs'] = 'COUNT(DISTINCT ContributorsSong.song_id)'; 

並刪除: 'COUNT(DISTINCT ContributorsSong.song_id)AS Contributor__TotalSongs',

而且它適用於現在訂購,但我不能在conditions中使用它。我認爲這是Limitations of virtualFields的一部分?我試圖只選擇TotalSongs> 0的表格,但我認爲我可以通過另一種方式,將連接從LEFT改爲INNER。