Join query of two databases in codeigniter

后端 未结 2 1220
旧时难觅i
旧时难觅i 2020-12-11 05:47

I need to write a join query of two tables from two databases and fetch the joined data. For eg, consider I have a database db1 which has some tables named companies, plans,

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

    You can just give the following if you need to join two database tables:

    function get_per_company_total_use ($custid)
            {         
                     $this->db->select('Kalix2.ph_Companies.CompanyName');
                     $this->db->where('Kalix2.ph_Companies.Cust_ID', $custid);
                     $this->db->select_sum('Asterisk.cdr.call_length_billable')->from('Asterisk.cdr');
                     $this->db->group_by('Asterisk.cdr.CompanyName');
                     $this->db->join('Kalix2.ph_Companies', 'Kalix2.ph_Companies.CompanyName = Asterisk.cdr.CompanyName');
                     $query = $this->db->get();
                     if($query->result()){
                         foreach ($query->result() as $value) {
                             $companies[]= array($value->CompanyName,$value->call_length_billable);
                              }
                         return $companies;
                     }
                     else 
                         return FALSE;
            }
    

    Here actually you need not give the connection variable DB1 or DB2, just give $this->db.

    0 讨论(0)
  • 2020-12-11 05:57

    I'm having table x in DB1 which contain id, name and y_id. In DB2 there is a y table with id and name

    so if you need to get name of x and y in a same query the here is your answer:

        $db = $this->load->database("DB2", TRUE);
        $DB = $this->load->database("DB1", TRUE);
        $DB->select('x.name as name1, y.name as name2');
        $DB->from('x');
        $DB->join($db->database.'.y','x.y_id = y.id');
        $res = $DB->get();
    
    0 讨论(0)
提交回复
热议问题