2014-02-26 63 views
0

我有一個用戶模型,名稱,姓氏,電子郵件,former_surnames。還有AdditionalEmail模式,我在那裏爲用戶存儲額外的電子郵件。每個用戶可以有多個額外的電子郵件。各個模型中分別有關係hasMany和belongsToMany。 我必須搜索姓氏,former_surnames,電子郵件和附加電子郵件。我試圖使用可容忍的行爲,並創建了以下表格進行查詢:跨多個表選擇不同的查詢

$options['joins'] = array(
    array(
     'table' => 'users', 
     'alias' => 'User', 
     'type' => 'LEFT', 
     'conditions' => array('User.id = AdditionalEmail.user_id') 
    )); 
$options['conditions'] = array('OR' => array(
    'User.surname LIKE' => $search, 
    'User.former_surnames LIKE' => $search, 
    'User.email LIKE' => $search, 
    'AdditionalEmail.email LIKE' => $search)); 
$options['recursive'] = -1; 
$options['fields'] = 'DISTINCT User.username, User.name, User.surname, User.former_surnames'; 
$options['order'] = array('User.surname' => 'asc'); 

上面,但是沒有爲我工作。我終於結束了與查詢:

SELECT DISTINCT users.* FROM users LEFT JOIN additional_emails ON (users.id = additional_emails.user_id) WHERE ((additional_emails.email LIKE \''. $search .'\') OR (users.email LIKE \''. $search .'\') OR (users.surname LIKE \''. $search .'\') OR (users.former_surnames LIKE \''. $search .'\')) ORDER BY users.surname 

它工作正常。如何使用cakephp選項爲查找(或分頁)構建此查詢。 Registers Piotr

回答

0
$this->User->find('all', 
    array(
     'fields' => array('DISTINCT *'), 
     'joins' => array(
       array(
        'table' => 'additional_emails', 
        'alias' => 'Email', 
        'type' => 'left', 
        'conditions' => array('User.id = Email.user_id') 
       ), 
     ), 
      'conditions' => array(
       'OR' => array(
        'Email.email LIKE' => $search, 
        'User.email LIKE' => $search, 
        'User.surname LIKE' => $search, 
        'User.former_surnames LIKE' => $search, 
       ) 
     ), 
      'order' => array('User.surname'), 
    ) 
); 
+0

謝謝啓,這完美的作品。 – Piotr