【问题标题】:Return results when search parameters is null i Zend Lucene当搜索参数为空时返回结果 i Zend Lucene
【发布时间】:2012-03-19 09:53:43
【问题描述】:

我在搜索表单中有多个字段。每个字段都可以为空。 我这样构建查询:

$search_title = trim($_POST["search_title"]);
$search_skill = trim($_POST["search_skill"]);
$search_company = trim($_POST["search_city"]);
$search_country_id = trim($_POST["search_county_id"]);

$hits = $index->find("title:$search_title and skill:$search_skill and city:$search_city and country_id:$country_id");

用户只能填写职务或技能或城市等,但如果某些字段为空,我将没有结果。 只有当所有字段都填写并匹配时,我才有结果。 如果只填写一个字段,我不会得到结果,如果为空则忽略该字段:

$hits = $index->find("title: and skill: and city: and country_id:$country_id");    

【问题讨论】:

标签: php zend-framework zend-search-lucene


【解决方案1】:

你可以试试这样的:

if ($this->getRequest()->isPost()) {
            if ($form->isValid($this->getRequest()->getPost)) {
                //get filtered and valid values from search form.
                //filter the array for set values
                $data = array_filter($form->getValues());
                //extract key => vaules as $variable = values
                extract($data);
                 $query1 = new Zend_Search_Lucene_Search_Query_MultiTerm();
                 //test for variable isset and add term to query
                 if (isset($search_title)){
                     $query1->addTerm(new Zend_Search_Lucene_Index_Term($search_title, 'title'));
                 }
                 if (isset($search_skill)){
                     $query1->addTerm(new Zend_Search_Lucene_Index_Term($search_skill, 'skill'));
                 }
                 if (isset($search_city)){
                     $query1->addTerm(new Zend_Search_Lucene_Index_Term($search_city, 'city'));
                 }
                 if (isset($search_country_id)){
                     $query1->addTerm(new Zend_Search_Lucene_Index_Term($search_country_id, 'country_id'));
                 }
                 //This should give the AND you are looking for...I hope
                 $query= new Zend_Search_Lucene_Search_Query_Boolean(array($query1), array(TRUE));
                 //get result set from query
                 $hits = $index->find($query);
            }
        }

如果您在表单中使用StringTrim 过滤器,则无需对数据使用trim() 函数。 $_POST 数组对用户提供的数据很危险,ZF 提供了getValues() 系列方法来提供来自请求对象(PO​​ST 和 GET)的数据,这些数据已经应用了您指定的过滤器和验证器。
我在本例中使用了extract() 函数,因为我使用了getValues(),因此数据已被过滤和验证。当然还有其他有效的方法可以将key => value 对分配给变量。使用你最喜欢的。

【讨论】:

  • 这个查询全部返回:search_title OR search_skill OR search_city 等,但我需要 search_title AND search_skill 等。
猜你喜欢
  • 2016-02-27
  • 1970-01-01
  • 2011-09-26
  • 1970-01-01
  • 1970-01-01
  • 2014-03-27
  • 1970-01-01
  • 2021-12-02
  • 1970-01-01
相关资源
最近更新 更多