在CakePHP中从多字搜索查询中形成查找条件

时间:2011-07-18 06:45:12

标签: search cakephp

我的产品包含多个可搜索的字段(名称,文字,产品代码等)。

我想要做的是爆炸搜索字符串并确保在记录的某处找到每个单词。

我通常会说一句话:

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

现在我觉得我必须制作与搜索字符串一样多的OR数组,并将它们全部包含在AND数组中。我只是不知道如何编码。

1 个答案:

答案 0 :(得分:6)

这样的事情应该这样做

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

编辑:如果您的所有搜索字词都必须出现在任何字段中,则可能是这样的:

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