我刚刚将Laravel的数据库层Eloquent包含在我的CodeIgniter 3项目中.然而,我的问题是我无法使用Eloquent模型连接到多个数据库.
对于默认DB,这是我配置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();
以上效果很好.但我有一个来自另一个数据库的员工表.我可以使用查询构建器来使用它,但是使用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连接到多个数据库?如果有,怎么样?
雄辩的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";