2009-12-28 79 views
3

就在幾天前,我發現了這個叫做CakePHP的奇蹟,所以我對它很綠。 我需要建立一個郵件應用程序,所以我遵循了約定,並創建:命名約定並加入CakePHP

數據庫描述:

用戶的表<的user_id(主鍵),FNAME,LNAME>。

郵件表< mail_id(主鍵),從(外鍵到user_id),到(外鍵到user_id),內容,打開>。

我的問題:

1)按照慣例,一個外鍵應該被稱爲相關表+ '_ ID'。如果有兩個涉及同一個表的外鍵,我應該如何調用列。喜歡從郵件表到郵件表。

2)我想做一個內部JOIN兩個表之間。 喜歡的東西:

SELECT user_id, mail_id 
FROM users 
INNER JOIN mails 
ON users.user_id =mails.to AND mails.opened=false. 

但我不知道該怎麼做。

+1

雖然在約定的主題上,您應該簡單命名主鍵「id」,而不是「user_id」和「mail_id」。 :) – deceze 2009-12-28 23:22:42

回答

1

我不是專家,我自己,但CakePHP的網站下面的信息將進一步幫助你: Multiple-relations-to-the-same-model

+0

嗨, 感謝您的回覆。我看過教程,在他們的例子中,他們寫了一個$ this-> Recipe-> find()調用的示例結果。 但我真的無法知道什麼是寫在食譜 - >找到() – special0ne 2009-12-28 14:06:03

+0

然後你可能已經試驗了conplex查找以及(http://book.cakephp.org/view/73/Retrieving-Your-Data#複雜-FIND-條件-74)。 如果失敗,可以使用$ this-> Recipe-> query($ sqlStatement)。 – 2009-12-28 14:30:52

+0

Recipe :: find()函數是從父類繼承的,因此您不必編寫它。它是爲你寫的。如果您的意思是傳遞給函數的參數,那麼在手冊中有很好的文檔記錄。我建議你做蛋糕教程,開始完成,這應該可以幫助你解決這些基本問題。 – 2009-12-28 16:32:35

4

當你需要做兩個關係同桌,你需要重寫默認的慣例。在你的例子中,我會做2個外鍵。一個名爲sender_id和一個名爲recipient_id。然後,你會加入他們的型號,像這樣:

<?php 

class Mail extends AppModel { 
    //The Associations below have been created with all possible keys, those that are not needed can be removed 
    var $belongsTo = array(
     'UserSender' => array(
      'className' => 'User', 
      'foreignKey' => 'sender_id', 
      'conditions' => '', 
      'fields' => '', 
      'order' => '' 
     ), 
      'UserRecipient' => array(
      'className' => 'User', 
      'foreignKey' => 'recipient_id', 
      'conditions' => '', 
      'fields' => '', 
      'order' => '' 
     ), 
    ); 
} 
?> 

然後做你的條件,你會引用它們像這樣:

<?php 
    $this->Mail->find(array('conditions'=>array('Mail.opened'=>false))); 
?> 

......並在發送者和接收者過濾,您的條件將如下所示:

<?php 
    $this->Mail->find(array('conditions'=>array('UserSender.some_field'=>$someValue, 
               'UserRecipient.some_field'=>$someValue))); 
?>