【问题标题】:Cakephp - Search with AND and OR conditionsCakephp - 使用 AND 和 OR 条件搜索
【发布时间】:2013-02-05 04:35:32
【问题描述】:

我正在尝试实现所有字段都是可选的搜索,因此我必须根据用户输入过滤我的结果,但我一直坚持如何实现这一点......

搜索字段如下

1) 通过电子邮件搜索:

2) 按名称搜索:

3) 按注册日期搜索:(即 fromDate 和 toDate)

选项 1) 和 3) 能够实现,因为只需要一个 AND 条件。

问题在于选项 2) name 应该匹配 first_name 或 last_name,所以我必须有一个 OR 条件,我无法找到正确的方法..

注意:所有字段都是可选的...

这是我的代码 sn-p....

$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 中生成这个查询,但是它是静态的,我正在寻找一种动态的方式来生成这个查询,因为搜索字段是可选的,并且查询应该根据用户输入而改变.....

【问题讨论】:

    标签: php cakephp search


    【解决方案1】:

    要将 LIKE 运算符与 % 通配符一起使用,您可以:

            'OR' => array(
                'User.first_name LIKE' => "%" . $this->request->data['searchbyname'] . "%",
                'User.last_name LIKE' => "%" . $this->request->data['searchbyname'] . "%"
            ),
    

    【讨论】:

    • 这对我有用,谢谢指出我一直在使用的语法错误......
    猜你喜欢
    • 2020-02-19
    • 2019-08-31
    • 2016-04-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多