2012-07-16 33 views
2

所以我有這個查詢,我試圖轉換爲蛋糕ORM,我不知道如何去做。轉換SQL到cakephp ORM

我有一個用戶表和一個單詞表。用戶有很多單詞(多數民衆贊成關係)。我想寫一個查詢,它會給我添加系統中最多單詞的用戶。這是我寫的當前查詢,但我無法將其轉換爲cakephp ORM語法,有什麼想法?

SELECT 
    users.username, 
    COUNT(word) AS n 
FROM 
    users AS users 
     INNER JOIN words AS words 
      ON users.userid=words.userid 
GROUP BY 
    users.username 
ORDER BY 
    n DESC 
LIMIT 3 

回答

3

有很多方法來編寫查詢: - 在控制器,你可以寫 -

$options = array(
      'fields' => array(
        'User.name', 
        'COUNT(Word.id) as word_count', 
       ), 
      'group' => 'Word.user_id', 
      'order' => 'word_count DESC', 
     );   

$users = $this->User->Word->find('first', $options); 
debug($users); 

在用戶模式,你必須寫:

public $hasMany = 'Word'; 

在Word模型,你必須寫:

public $belongsTo = 'User';