2

我正在尝试搜索多个单词。我已经尝试将 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 的 Active Record 或“$this->get->query”实现多词搜索。

4

2 回答 2

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');
于 2012-08-26T12:32:36.470 回答
1

你得到这个结果是因为你在单个分隔的字段上运行了类似的句子。取而代之的是,您可以尝试先连接字段,然后对结果运行查询,就像这样:

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

$this->db->query($sql);
于 2012-08-26T12:44:47.490 回答