Multiple database connection using Illuminate/Database Eloquent ORM in CodeIgniter 3

百般思念 提交于 2019-12-10 18:15:59

问题


I have just included Laravel's database layer Eloquent to my CodeIgniter 3 project. My problem however is that I can't connect to multiple databases using Eloquent models.

For the default DB, this is how I configured the DB:

$capsule = new Capsule;

$capsule->addConnection(array(
        'driver'    => 'mysql',
        'host'      => "localhost",
        'database'  => "employees_db",
        'username'  => "root",
        'password'  => "",
        'charset'   => 'utf8',
        'collation' => 'utf8_unicode_ci',
        'prefix'    => '',
        ));

$capsule->setAsGlobal();
$capsule->bootEloquent();

The above works well. But I have an employee table from another database. I can use it using query builder, but fails with Eloquent models.

I tried this:

$employees = new Capsule;

$employees->addConnection(array(
        'driver'    => 'mysql',
        'host'      => "host2",
        'database'  => "employees_db",
        'username'  => "user",
        'password'  => "pass",
        'charset'   => 'utf8',
        'collation' => 'utf8_unicode_ci',
        'prefix'    => '',
        ),'employees');

$employees->setAsGlobal();

Tried setting up an Eloquent model and using the connection like:

protected $connection = "employees";

Is it possible to connect to multiple databases using Illuminate\Database Eloquent ORM outside of Laravel? If yes, how?


回答1:


Eloquent ORM needs to be initialized only once. Add the optional second parameter as the connection name.

$capsule = new Capsule;

$capsule->addConnection(
    array(
        'driver'    => 'mysql',
        'host'      => "localhost",
        'database'  => "employees_db",
        'username'  => "root",
        'password'  => "",
        'charset'   => 'utf8',
        'collation' => 'utf8_unicode_ci',
        'prefix'    => '',
    ),
    "default"
);

$capsule->addConnection(
    array(
            'driver'    => 'mysql',
            'host'      => "192.168.1.1",
            'database'  => "employees_db2",
            'username'  => "user",
            'password'  => "password",
            'charset'   => 'utf8',
            'collation' => 'utf8_unicode_ci',
            'prefix'    => '',
    ),
    "employees"
        );

$capsule->setAsGlobal();
$capsule->bootEloquent();

When the above has been setup, you can then assign which database to connect to in your model file by writing the code below:

protected $connection = "employees";


来源:https://stackoverflow.com/questions/34649181/multiple-database-connection-using-illuminate-database-eloquent-orm-in-codeignit

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!