2013-07-03 92 views
0

我在CakePHP的新手,想實現這個查詢CakePHP的使用JOIN在find方法

SELECT DISTINCT textmessage.mobileNo FROM textmessage 
JOIN contacts 
    ON textmessage.User_id=contacts.User_id AND textmessage.mobileNo = Contacts.mobileNo 

我在這裏希望只有一個結果..想在文字信息來實現此查詢控制器...我從來沒有使用聯接查詢之前在CakePHP ...我有兩個表實際上是一個mobileNo場,我想找回mobileNo如果mobileNo的TextMessage的表也是聯繫

這裏是我根據我的質量要求修改您的查詢..

$this->bindModel(array('belongsTo' => array('Contact' => array('className' => 'Contact', 
     'foreignKey' => false, 
     'conditions' => array('Message.user_id = Contact.user_id','Message.mobileNo = Contact.mobileNo')))), true); 

    return $message_details = $this->find('all', array('conditions' => array(), 
     'fields' => array('DISTINCT mobileNo'))); 

回答

1

將下面的代碼在你的控制器代碼:

如果你只需要一個記錄:

function test1() 
{ 
$this->TextMessage->bindModel(array('belongsTo' => array('Contact' => array('className' => 'Contact', 
             'foreignKey' => false, 
             'conditions' => array('TextMessage.user_id = Contact.user_id')))), false); 
$message_details = $this->TextMessage->find('all', array('conditions' => array(), 
              'fields' => array('DISTINCT mobileNo'))); 

} 

如果你有對應於每個接觸多個短信,然後嘗試以下方法:

function test2() 
{ 
$this->Contact->bindModel(array('hasMany' => array('TextMessage' => array('className' => 'TextMessage', 
             'foreignKey' => false, 
             'conditions' => array('TextMessage.user_id = Contact.user_id'), 
             'fields' => array('DISTINCT mobileNo'))) 
        ), false); 
$message_details = $this->Contact->find('all', array('conditions' => array()));     
} 

您也可以在模型中編寫關聯。我舉了一個例子來動態地加入任何表格。

根據你編輯的問題,如果你不需要兩個數組。使用query()函數。

希望這能滿足您的要求。

+0

@Arjun Jain謝謝Arjun ..但是你沒有在你的查詢中使用「distinct」? – hellosheikh

+0

以及當我運行你的第一個查詢..它不給我所需的結果。 – hellosheikh

+0

我在哪裏得到您的查詢mobileNo也沒有明顯的用途? – hellosheikh