简体   繁体   中英

convert the mysql query to codeigniter 3 model

Convert the MySQL query to Codeigniter Query

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

I have tried to convert it in 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')

The top one is in MySQL and bottom which I try to convert is in Codeigniter I m trying to search the keyword from selected columns from three tables. How I can convert the MySQL to Codeigniter. I'm trying to search the keyword from selected columns from three tables.

How I can convert the MySQL to Codeigniter

Try this

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

Note:- If you intend to use this make sure that your both the table column are same sequence and name.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM