2012-08-26 69 views
2

我正在嘗試搜索多個單詞。我已經嘗試在我的數據庫模式中添加FULLTEXT。CodeIgniter ActiveRecord FULLTEXT多個詞搜索

這是我現在的代碼,只有一個單詞返回結果。

$term = $this->input->post('term'); 

$this->db->like('firstname', $term); 
$this->db->or_like('lastname', $term); 
$this->db->or_like('middlename', $term); 

$query = $this->db->get('people'); 
$data['people'] = $query->result(); 
$this->load->view('people', $data); 

搜索「John」或「Doe」或「Smith」這樣的單詞是有效的。

但是,當我嘗試搜索「John Doe」或「John Doe Smith」時,它不會返回任何結果。

如何通過使用CodeIgniter的活動記錄或「$ this-> get-> query」來實現多個單詞搜索。

+0

如果你想使用全文索引,則必須使用'MATCH()'和'AGAINST()'MySql函數。 – DanMan

回答

5

試試這個:

$terms = explode(' ', $term); 

foreach($terms as $term){ 
    $this->db->or_like('firstname', $term); 
    $this->db->or_like('lastname', $term); 
    $this->db->or_like('middlename', $term); 
} 


$query = $this->db->get('people'); 

編輯:(您的評論之後)

$parts = substr_count(trim($term), ' '); 

    switch($parts){ 
     case 0: 
      $this->db->or_like('firstname', $term); 
      $this->db->or_like('lastname', $term); 
      $this->db->or_like('middlename', $term); 
      break; 
     case 1; 
      $this->db->or_like('CONCAT(firstname, " ", middlename)', $term); 
      $this->db->or_like('CONCAT(firstname, " ", lastname)', $term); 
      $this->db->or_like('CONCAT(middlename, " ", lastname)', $term); 
      break; 
     case 2: 
     default: 
      $this->db->or_like('CONCAT(firstname, " ", middlename, " ", lastname)', $term); 
      break; 

    } 

    $query = $this->db->get('people'); 
+0

這可以工作,但如果你有多個相似的名字,它會輸出很多結果。無論如何要更具體地匹配所有這些嗎?例如,如果我搜索「John Doe」,並且還有「Jane Doe」,則只會顯示我的搜索詞。謝謝。 – Tux

+0

@Tux更新。你可以開發另一個條件 – ADev

+0

這工作得很好,謝謝你Adev =) – Tux

1

你得到的結果,因爲你運行在單一的分離領域類似的句子。取而代之的是,U可以嘗試Concat的領域第一&然後運行在結果中查詢,就像這樣:

$sql = "SELECT * FROM people WHERE CONCAT(firstname,' ', middlename,' ', lastname) LIKE '%$term%'"; 

$this->db->query($sql);