使用CodeIgniter 3中的Illuminate / Database Eloquent ORM进行多个数据库连接

时间:2016-01-07 07:04:51

标签: php eloquent illuminate-container

我刚刚将Laravel的数据库层Eloquent包含在我的CodeIgniter 3项目中。然而,我的问题是我无法使用Eloquent模型连接到多个数据库。

对于默认数据库,这是我配置数据库的方式:

$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();

以上效果很好。但我有一个来自另一个数据库的员工表。我可以使用查询构建器来使用它,但是使用Eloquent模型会失败。

我试过了:

$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();

尝试设置Eloquent模型并使用如下连接:

protected $connection = "employees";

是否可以使用Laravel之外的Illuminate \ Database Eloquent ORM连接到多个数据库?如果是,怎么样?

1 个答案:

答案 0 :(得分:14)

雄辩的ORM只需要初始化一次。添加可选的第二个参数作为连接名称。

$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();

如果已经设置了上述内容,您可以通过编写以下代码来指定模型文件中要连接的数据库:

protected $connection = "employees";