在多个表中选择不同的查询

时间:2014-02-26 14:34:40

标签: mysql cakephp join distinct

我有一个名称,姓氏,电子邮件,以前名字的用户模型。还有AdditionalEmail模型,我为用户存储其他电子邮件。每个用户可以有多个额外的电子邮件。每个模型中都有关系hasMany和belongsToMany。 我必须搜索姓氏,姓名,电子邮件和附加电子邮件。我尝试使用可包含的行为并为查询创建了下表:

$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选项为find(或paginate)构建此查询。 问候 彼得

1 个答案:

答案 0 :(得分: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'),
     )
 );