Henri
Henri

Reputation: 740

Forming find conditions from multi word search query in CakePHP

I have products with multiple fields than can be searched (name, text, product code, etc).

What I want to do is explode the search string and make sure that every word is found somewhere at the record.

With one word I would normally do like:

'OR'=>array(
    'name LIKE'=>'%' . $oneword . '%',
    'text LIKE'=>'%' . $oneword . '%',
    'code LIKE'=>'%' . $oneword . '%',
 )

Now I feel that I have to make as many OR-arrays as search string has words and include them all in AND-array. I just don't know how to code it.

Upvotes: 2

Views: 2976

Answers (2)

Disgusted Zombie
Disgusted Zombie

Reputation: 1

$search_terms = explode(' ', $search_text);
foreach ($search_terms as $search_term) 
{
    $conditions[] = ['OR' => [
        'cohortes.titre LIKE' => '%' . $search_term . '%',
        'cohortes.code LIKE' => '%' . $search_term . '%',
        ],
    ];
}

Upvotes: 0

kaklon
kaklon

Reputation: 2432

Something like this should do it

$conditions = array();
$search_terms = explode(' ', $search_string);
foreach($search_terms as $search_term){
    $conditions[] = array('Model.name Like' =>'%'.$search_term.'%');
    $conditions[] = array('Model.text Like' =>'%'.$search_term.'%');
    $conditions[] = array('Model.code Like' =>'%'.$search_term.'%');
}
$products = $this->paginate('Product', array('conditions' => array('OR' => $conditions)));

Edit: If all your search term must be present in any of the fields, it would be something like this:

$conditions = array();
$search_terms = explode(' ', $search_string);
foreach($search_terms as $search_term){
    $conditions[] = array('OR' => array('Model.name Like' =>'%'.$search_term.'%',
                                        'Model.text Like' =>'%'.$search_term.'%',
                                        'Model.code Like' =>'%'.$search_term.'%',
                                  )
                          );
}
$products = $this->paginate('Product', $conditions); 

Upvotes: 6

Related Questions