PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Saturday, April 2, 2022

[FIXED] Forming find conditions from multi word search query in CakePHP

 April 02, 2022     cakephp, search     No comments   

Issue

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.


Solution

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); 


Answered By - kaklon
Answer Checked By - Dawn Plyler (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing