title: Cakephp - Search with AND and OR conditions
body: <p>I am trying to implement a search in which all fields are optional, so i have to filter my results based on user input, but am stuck on how to achieve this...</p>
  
  <p>The search field is as follows</p>
  
  <p>1) serach by email : </p>
  
  <p>2) serach by name :</p>
  
  <p>3) serach by registration date : (i.e fromDate and toDate) </p>
  
  <p>options 1) and 3) am able to achieve as only an AND condition is required.</p>
  
  <p>problem is with option 2) name should match either first_name or last_name, so i must have an OR condition , which i cant figure out a right way to do it..</p>
  
  <p>Note: All fields are optional...</p>
  
  <p>heres my code snippet....</p>
  
  <pre><code>$conditions = array();
  
  if(!empty($this-&gt;request-&gt;data['searchbyemail'])) {
  
     $conditions[] = array('User.username' =&gt; $this-&gt;request-&gt;data['searchbyemail']);
  }
  
  if(!empty($this-&gt;request-&gt;data['regfromdate']) &amp;&amp;
     !empty($this-&gt;request-&gt;data['regtodate'])) {
  
      $conditions[] = array('User.created BETWEEN ? AND ?' =&gt; 
      array($this-&gt;request-&gt;data['regfromdate'], $this-&gt;request-&gt;data['regtodate']));
  }
  
  if(!empty($this-&gt;request-&gt;data['searchbyname'])) {
  
      $conditions[] = array(
  'OR' =&gt; array(
          'User.first_name' =&gt; $this-&gt;request-&gt;data['searchbyname'],
          'User.last_name' =&gt; $this-&gt;request-&gt;data['searchbyname']
  
                  ));
  }
  
  
  $this-&gt;paginate = array('conditions' =&gt; $conditions);
  $this-&gt;set('users', $this-&gt;paginate());
  </code></pre>
  
  <p>The query am trying to achieve should look like this</p>
  
  <pre><code>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%'))
  </code></pre>
  
  <p>Am able to generate this query in cakephp but its static , am looking for a dynamic way to generate this query since the search fields are optional and the query should change according to the user input.....</p>