简体   繁体   English

Codeigniter 3 与 dbforge 的多个数据库连接

[英]Codeigniter 3 multiple database connections with dbforge

I am building a web app with CI 3, I have to use 2 different database connections for certain requirement.我正在使用 CI 3 构建一个 Web 应用程序,我必须使用 2 个不同的数据库连接来满足某些要求。 I have loaded the configuration to the database.php file and I can of course connect to them using the built in classes.我已将配置加载到 database.php 文件,当然我可以使用内置类连接到它们。

$db['default'] = array(
    'dsn' => '',
    'hostname' => 'localhost',
    'username' => 'root',
    'password' => 'root',
    'database' => 'primary',
    'dbdriver' => 'mysqli'
);

$db['customer'] = array(
    'dsn' => '',
    'hostname' => 'localhost',
    'username' => 'root_1',
    'password' => 'root_1',
    'database' => 'secondary',
    'dbdriver' => 'mysqli'

);

I am using a MY_Model from here .我正在使用这里的 MY_Model 。 So I extend them as follows..所以我将它们扩展如下..

class Table extends MY_Model
{


    public function __construct()
    {

        parent::__construct();

        $this->_database = $this->load->database('customer', TRUE);
    }

    public function create_table()
    {
    return $this->_database->query("CREATE TABLE MyGuests (
                      id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
                      firstname VARCHAR(30) NOT NULL,
                      lastname VARCHAR(30) NOT NULL,
                      email VARCHAR(50),
                      reg_date TIMESTAMP
                    )");

    }

}

But I need to use dbForge to create tables.但我需要使用 dbForge 来创建表。 But only 'default' connection is used with the dbForge class.但是只有“默认”连接与 dbForge 类一起使用。 Codeigniter dbForge documentation doesn't give a way to load different db connections to the dbForge. Codeigniter dbForge 文档没有提供将不同数据库连接加载到 dbForge 的方法。 Anyone know how to tackle the issue in an elegant way?任何人都知道如何以优雅的方式解决这个问题?

After little bit research I found the right way to do it.经过一点研究,我找到了正确的方法。

$this->load->dbForge() can actually take a parameter, If we pass a database object it will use that connection to perform the operation. $this->load->dbForge()实际上可以带一个参数,如果我们传递一个数据库对象,它将使用该连接来执行操作。

In addition, we can pass a second argument and get a separate object as well.此外,我们还可以传递第二个参数并获得一个单独的对象。

$this->dbForgeSecondary = $this->load->dbforge($this->_database, TRUE);

Easy & Pretty Cool.简单而酷。

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

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