CodeIgniter ActiveRecord FULLTEXT多字搜索

时间:2012-08-26 12:15:16

标签: php mysql codeigniter

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

2 个答案:

答案 0 :(得分: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');

答案 1 :(得分:1)

你得到的结果是因为你在单个分隔的字段上运行了类似的句子。而不是那样,你可以先尝试将这些字段连接起来。然后在结果上运行查询,如下所示:

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

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