开发者

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 r开发者_运维问答ecord.

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.


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


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜