CodeIgniter ActiveRecord FULLTEXT多词搜索


CodeIgniter ActiveRecord FULLTEXT Multiple Words Search

我正在尝试搜索多个单词。我已经尝试将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"来实现多个单词的搜索。

试试这个:

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

您之所以得到这样的结果,是因为您在单独分隔的字段上运行了类似的语句。相反,你可以尝试先连接字段&然后对结果运行查询,如下所示:

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