Cakephp-使用AND和OR条件进行搜索
我正在尝试实现一个搜索,其中所有字段都是可选的,因此我必须根据用户输入筛选结果,但我一直在思考如何实现这一点 搜索字段如下所示 1) serach通过电子邮件: 2) 瑟拉赫(姓名): 3) 按注册日期划分的serach:(即fromDate和toDate) 选项1)和3)我能够实现,因为只需要一个和条件 问题在于选项2)名称应该与名字或姓氏匹配,所以我必须有一个or条件,我无法找到正确的方法来实现 注意:所有字段都是可选的 这是我的代码片段Cakephp-使用AND和OR条件进行搜索,php,cakephp,search,Php,Cakephp,Search,我正在尝试实现一个搜索,其中所有字段都是可选的,因此我必须根据用户输入筛选结果,但我一直在思考如何实现这一点 搜索字段如下所示 1) serach通过电子邮件: 2) 瑟拉赫(姓名): 3) 按注册日期划分的serach:(即fromDate和toDate) 选项1)和3)我能够实现,因为只需要一个和条件 问题在于选项2)名称应该与名字或姓氏匹配,所以我必须有一个or条件,我无法找到正确的方法来实现 注意:所有字段都是可选的 这是我的代码片段 $conditions = array(); if
$conditions = array();
if(!empty($this->request->data['searchbyemail'])) {
$conditions[] = array('User.username' => $this->request->data['searchbyemail']);
}
if(!empty($this->request->data['regfromdate']) &&
!empty($this->request->data['regtodate'])) {
$conditions[] = array('User.created BETWEEN ? AND ?' =>
array($this->request->data['regfromdate'], $this->request->data['regtodate']));
}
if(!empty($this->request->data['searchbyname'])) {
$conditions[] = array(
'OR' => array(
'User.first_name' => $this->request->data['searchbyname'],
'User.last_name' => $this->request->data['searchbyname']
));
}
$this->paginate = array('conditions' => $conditions);
$this->set('users', $this->paginate());
我试图实现的查询应该如下所示
SELECT * FROM `users` AS `User`
WHERE `User`.`username` = 'a'
AND `User`.`created`
BETWEEN '2013-02-01'
AND '2013-02-05'
AND ((`User`.`first_name` LIKE '%b%')) OR ((`User`.`last_name` LIKE '%b%'))
我可以用cakephp生成此查询,但它是静态的,我正在寻找一种动态的方法来生成此查询,因为搜索字段是可选的,查询应该根据用户输入进行更改…..要使用带有%通配符的
LIKE
运算符,您应该:
'OR' => array(
'User.first_name LIKE' => "%" . $this->request->data['searchbyname'] . "%",
'User.last_name LIKE' => "%" . $this->request->data['searchbyname'] . "%"
),
要将
LIKE
运算符与%通配符一起使用,您需要:
'OR' => array(
'User.first_name LIKE' => "%" . $this->request->data['searchbyname'] . "%",
'User.last_name LIKE' => "%" . $this->request->data['searchbyname'] . "%"
),
这对我来说是个窍门谢谢你指出了我使用的语法错误这对我来说是个窍门谢谢你指出了我使用的语法错误。。。。。。