将mysql查询转换为codeigniter 3模型

时间:2019-03-29 05:11:04

标签: mysql codeigniter

将MySQL查询转换为Codeigniter查询

    $query = "(SELECT content, title, 'msg' as type FROM messages WHERE content LIKE '%" . 
               $keyword . "%' OR title LIKE '%" . $keyword ."%') 
               UNION
               (SELECT content, title, 'topic' as type FROM topics WHERE content LIKE '%" . 
               $keyword . "%' OR title LIKE '%" . $keyword ."%') 
               UNION
               (SELECT content, title, 'comment' as type FROM comments WHERE content LIKE '%" . 
               $keyword . "%' OR title LIKE '%" . $keyword ."%')";

    mysql_query($query);

我试图将其转换为Codeigniter

              $this->db->like("content", $keyword);

              $this->db->or_like('title',$keyword,'after'); 
              $this->db->or_like('msg',$keyword,'after'); 
             ->from('message')
              $this->db->like("content", $keyword);
              $this->db->or_like('title',$keyword,'after'); 
              $this->db->like("msg", $keyword);
             ->from('topics')
              $this->db->or_like('content',$keyword,'after'); 
              $this->db->or_like('title',$keyword,'after'); 
              $this->db->or_like('msg',$keyword,'after'); 
              ->from('comment')

顶部是MySQL,底部是Codeigniter,我试图从三个表的选定列中搜索关键字。我如何将MySQL转换为Codeigniter。我正在尝试从三个表的选定列中搜索关键字。

如何将MySQL转换为Codeigniter

1 个答案:

答案 0 :(得分:1)

尝试一下

$this->db->select('content, title, msg as type');
$this->db->from('message');
$this->db->like("content", $keyword);
$this->db->or_like('title',$keyword,'after'); 
$this->db->or_like('msg',$keyword,'after'); 
$query1 = $this->db->get_compiled_select();


$this->db->select('content, title, msg as type');
$this->db->from('topics');
$this->db->like("content", $keyword);
$this->db->or_like('title',$keyword,'after'); 
$this->db->like("msg", $keyword);
$query2 = $this->db->get_compiled_select();

$this->db->select('content, title, msg as type');
$this->db->from('comment');
$this->db->or_like('content',$keyword,'after'); 
$this->db->or_like('title',$keyword,'after'); 
$this->db->or_like('msg',$keyword,'after'); 
$query3 = $this->db->get_compiled_select();

$result = $this->db->query($query1." UNION ".$query2." UNION ".$query3);
return $result->result();

注意:-如果要使用此功能,请确保两个表列的序列和名称都相同。