doutucui0133 2012-08-26 12:15
浏览 42
已采纳

CodeIgniter ActiveRecord FULLTEXT多字搜索

I'm trying to search for multiple words. I already, tried adding FULLTEXT to my database schema.

This is the code I have now, and only one word returns results.

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

Searching for one word like "John" or "Doe" or "Smith" works.

But when I try searching for "John Doe" or "John Doe Smith" it won't return any results.

How can I achive multiple words search by using CodeIgniter's Active Record or a "$this->get->query".

  • 写回答

2条回答 默认 最新

  • drze7794 2012-08-26 12:32
    关注

    Try this:

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

    EDIT: (after your comment)

      $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条)

报告相同问题?