03.29 php saved
polerin
Tags add more
AppModel and search  
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.     /**
  2.      * Search in the model for $term in $fields.  All members of $terms are exploded()'ed on ' '
  3.      *
  4.      * @return array of matches.
  5.      * @param {Array, String} $terms String or strings to search for
  6.      * @param {Array, String} $searchFields Field names
  7.      * @param {Array} $params Params to pass to find [Optional]
  8.      */
  9.     function searchConditions($terms, $searchFields, $params = array()) {
  10.  
  11.         //make sure everything we need is in array form
  12.         if (!is_array($searchFields)) {
  13.             $searchFields = explode(' ', $searchFields);
  14.         }
  15.  
  16.         if (!is_array($terms)) {
  17.             $terms = array($terms);
  18.         }
  19.  
  20.         $conditions = array();
  21.  
  22.         $term_buffer = array();
  23.    
  24.         foreach ($terms as $term) {
  25.             //merge it in
  26.             $term_buffer = array_merge($term_buffer, explode(' ', $term));
  27.         }
  28.  
  29.         while (!empty($term_buffer)) {
  30.             $term = array_shift($term_buffer);
  31.             $type = 'OR';
  32.             $not = ($term{0} == '-');
  33.    
  34.             // force/ignore word by prepending +/-
  35.             if (in_array($term{0}, array('+', '-'))) {
  36.                 $type = 'AND';
  37.                 $term = ltrim($term, '+-');
  38.             }
  39.             // handle protected strings
  40.             if ($term{0} == '"') {
  41.                 while (!empty($term_buffer) && substr($term, -1, 1) != '"') {
  42.                     $term .= " ".array_shift($term_buffer);
  43.                 }
  44.                 $term = trim($term, '"');
  45.             }
  46.             if ($term != '') {
  47.                 foreach ($searchFields as $field) {
  48.                     $not = ($not) ? "NOT " : "";
  49.                     $conditions[$type][] = "{$field} {$not}LIKE '%{$term}%'";
  50.                 }
  51.             }
  52.         }
  53.        
  54.        
  55.  
  56.         //set our params
  57.         $fields = $order = $page = $limit = null;
  58.         extract($params);
  59.            
  60.         //aaaaaaaand return!
  61.         return $this->findAll($conditions, $fields, $order, $page, $limit);
  62.     }
Parsed in 0.095 seconds, using GeSHi 1.0.7.14

Modify this Paste