gpt4 book ai didi

mysql - 跨多个表选择不同的查询

转载 作者:行者123 更新时间:2023-11-30 00:37:28 26 4
gpt4 key购买 nike

我有一个包含名字、姓氏、电子邮件、前姓氏的用户模型。还有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 查找(或分页)选项构建此查询。问候皮奥特尔

最佳答案

 $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'),
)
);

关于mysql - 跨多个表选择不同的查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22044549/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com