我正在尝试实现所有字段都是可选的搜索,因此我必须根据用户输入过滤我的结果,但我一直坚持如何实现这一目标......
搜索字段如下
1)通过电子邮件搜索:
2)按名称搜索:
3)按注册日期搜索:(即fromDate和toDate)
选项 1) 和 3) 能够实现,因为只需要 AND 条件。
问题在于选项 2)名称应该匹配 first_name 或 last_name,所以我必须有一个 OR 条件,我无法找到正确的方法来做到这一点..
注意:所有字段都是可选的...
这是我的代码片段....
$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 中生成这个查询,但是它是静态的,我正在寻找一种动态的方式来生成这个查询,因为搜索字段是可选的,并且查询应该根据用户输入而改变.....