简体   繁体   English

使用Codeigniter连接来自两个数据库的表

[英]Joining tables from two databases using codeigniter

In order to write query in codeigniter you need to write something like $this->db->query or $someDB->query . 为了在codeigniter中编写查询,您需要编写类似$this->db->query$someDB->query But what if I want to join tables from two different databases? 但是,如果我想联接来自两个不同数据库的表怎么办?

I know that I can do it through pure php, using mysqli_connect and writing something like: 我知道我可以通过纯php,使用mysqli_connect并编写如下内容来做到这一点:

SELECT * FROM db1.table1 JOIN db2.table2

But is there a way to do it using codeigniter? 但是有办法使用codeigniter吗?

Use query method from CodeIgniter and pass any complex sql query trough: 使用CodeIgniter的查询方法并传递任何复杂的sql查询槽:

$query = $this->db->query("SELECT * FROM dbname1.table t1 JOIN db2.table t2 ON t2.column = t1.column");

foreach ($query->result() as $row)
{
    print_r($row);
}

This simple join of student and teacher table with same column name , Hope you will get it . 带有相同列名称的学生和教师表的这种简单连接,希望您能得到。

$this->db->select("s.*,t.*");
$this->db->from("student as s");
$this->db->join("teacher as t","s.student_id = t.student_id","both");
$result = $this->db->get()->result_array();
return $result;

also you want single row try row_array(); 你也想单行尝试row_array(); instead of result_array(); 而不是result_array();

You can try to use the function I am using in a project I am working on right now... Please see the code below... 您可以尝试使用我现在正在处理的项目中使用的功能...请参见下面的代码...

function join_table()
{
    $this->db->select(//column name, //column name, //column name);
    $this->db->from(//table1 name);
    $this->db->join(//table2 name, //table1 name.//column name = //table2 name.//column name');
    $this->db->where(//condition);
    return $this->db->get()->result();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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