Write union query in codeigniter style

前端 未结 3 1254
余生分开走
余生分开走 2020-12-11 11:28

How can I write the following query in Codeigniter style.

SELECT COUNT(`id`) AS reccount
  FROM 
    (SELECT `id` FROM table1 
     WHERE tid= \'101\' AND `s         


        
相关标签:
3条回答
  • 2020-12-11 11:54

    You can use CI to generate a union query. However, latest versions made this much harder than before.

    DB has a method called _compile_select, in previous versions of CI it was public, however now it is protected so you can't just call $this->db->_compile_select() from your controller. In order to do this properly one could:

    1. Create custom loader class to be able to extend core/database classes (i.e. load MY_DB_active_record instead of CI_DB_active_record).
    2. Create custom activerecord class, with just one method:

      public function compile_select() {
          return $this->_compile_select();
      }
      
    3. In your controller, create all necessary queries, compile them into a string array using our public method compile_select()

    4. Join the array into single query: '(' . implode(') UNION (', $queries) . ')'. You can also wrap this into a separate method inside your custom AR class.
    0 讨论(0)
  • 2020-12-11 12:04

    Since CodeIgniter 3 it's been introduced in Active Record the function get_compiled_select() that gives the query string without actually executing the query.

    This allows @MDeSilva method to use less resources, being adapted as follows:

    function get_merged_result($ids){                   
        $this->db->select("column");
        $this->db->distinct();
        $this->db->from("table_name");
        $this->db->where_in("id",$model_ids);
        $query1 = $this->db->get_compiled_select(); // It resets the query just like a get()
    
        $this->db->select("column2 as column");
        $this->db->distinct();
        $this->db->from("table_name");
        $this->db->where_in("id",$model_ids);
        $query2 = $this->db->get_compiled_select(); 
    
        $query = $this->db->query($query1." UNION ".$query2);
    
        return $query->result();
    }
    
    0 讨论(0)
  • 2020-12-11 12:11
    function get_merged_result($ids){                   
        $this->db->select("column");
        $this->db->distinct();
        $this->db->from("table_name");
        $this->db->where_in("id",$model_ids);
        $this->db->get(); 
        $query1 = $this->db->last_query();
    
        $this->db->select("column2 as column");
        $this->db->distinct();
        $this->db->from("table_name");
        $this->db->where_in("id",$model_ids);
    
        $this->db->get(); 
        $query2 =  $this->db->last_query();
        $query = $this->db->query($query1." UNION ".$query2);
    
        return $query->result();
    }
    
    0 讨论(0)
提交回复
热议问题