03.29 php saved
nanoman
Tags add more
 
Note
Generic multi-field search Stick this in your AppModel. Original code by me, heavily refactored and added too by the excellent Mr. TommyO. This is a bug fixed version. Let me know if there's anything useful or wrong that you'd like added/fixed.
  1. <?php
  2. /**
  3. * Search in the model for $term in $fields.  All members of $terms are exploded()'ed on ' '
  4. *
  5. * @return array of matches.
  6. * @param {Array, String} $terms String or strings to search for
  7. * @param {Array, String} $searchFields Field names
  8. * @param {Array} $params Params to pass to find [Optional]
  9. */
  10. function searchConditions($terms, $searchFields, $params = array()) {
  11.  
  12.     $defaultParams = array(
  13.             'fields' => null,
  14.             'order' => null,
  15.             'page' => null,
  16.             'limit' => null,
  17.             'returnConditions' => false
  18.         );
  19.  
  20.     $params = array_merge($defaultParams, $params);
  21.  
  22.     //make sure everything we need is in array form
  23.     if (!is_array($searchFields)) {
  24.         $searchFields = explode(' ', $searchFields);
  25.     }
  26.  
  27.     if (!is_array($terms)) {
  28.         $terms = array($terms);
  29.     }
  30.  
  31.     $conditions = array();
  32.  
  33.     $term_buffer = array();
  34.  
  35.     foreach ($terms as $term) {
  36.         //merge it in
  37.         $term_buffer = array_merge($term_buffer, explode(' ', $term));
  38.     }
  39.  
  40.     while (!empty($term_buffer)) {
  41.         $term = array_shift($term_buffer);
  42.         $type = 'OR';
  43.         $not = ($term{0} == '-');
  44.  
  45.         // force/ignore word by prepending +/-
  46.         if (in_array($term{0}, array('+', '-'))) {
  47.             $type = 'AND';
  48.             $term = ltrim($term, '+-');
  49.         }
  50.         // handle protected strings
  51.         if ($term{0} == '"') {
  52.             while (!empty($term_buffer) && substr($term, -1, 1) != '"') {
  53.                 $term .= " ".array_shift($term_buffer);
  54.             }
  55.             $term = trim($term, '"');
  56.         }
  57.         if ($term != '') {
  58.             foreach ($searchFields as $field) {
  59.                 $not = ($not) ? "NOT " : "";
  60.                 $conditions[$type][] = "{$field} {$not}LIKE '%{$term}%'";
  61.             }
  62.         }
  63.     }
  64.    
  65.  
  66.     extract($params);
  67.    
  68.     if($params['returnConditions']) {
  69.         return $conditions;
  70.     }
  71.        
  72.     //aaaaaaaand return!
  73.     return $this->findAll($conditions, $params['fields'], $params['order'], $params['page'], $params['limit']);
  74. }
  75. ?>
Parsed in 0.130 seconds, using GeSHi 1.0.7.14

Modify this Paste