Reply to comment

How to Cake PHP Search method

Cake PHP is a powerful MVC Framework that I am really enjoying however sometimes I don't have enough time to find the way that Cake PHP do something like a search using a OR clause =D So if you were looking for a direct instruction here you are:

<?php
   
function search() {

       
// $k is a POST with the keyword search...     
       
$k = $this->data['Yourmodel']['search_key'];
       
       
$this->Yourmodel->recursive = 0;
       
// Displays all records if you didn't POST a keyword
       
if(empty($k)) {
           
$results = $this->paginate();
        }
        else {
           
$this->paginate = array('conditions'=>array('OR'=>array('Yourmodel.name LIKE'=>'%'.$k.'%', 'Yourmodel.email'=>$k)));
           
$results = $this->paginate('Yourmodel');
        }   
       
$this->set('search_results', $results);
    }
?>

The show is just here:
<?php $this->paginate = array('conditions'=>array('OR'=>array('Yourmodel.name LIKE'=>'%'.$k.'%', 'Yourmodel.email'=>$k))); ?>
- We need to pass an array 'conditions' and other array with our 'OR' clause.

So, that's it =D

Reply

  • Web page addresses and e-mail addresses turn into links automatically.
  • Allowed HTML tags: <a> <em> <strong> <cite> <code> <ul> <ol> <li> <dl> <dt> <dd>
  • Lines and paragraphs break automatically.

More information about formatting options