[英]Two Databases in Eloquent ORM without Laravel
我使用没有Laravel的Eloquent ORM,它可以正常使用一个数据库,但我不知道如何使用第二个数据库..我使用Capsule配置eloquent
DATABASE.PHP文件:
require 'vendor/autoload.php';
use Illuminate\Database\Capsule\Manager as Capsule;
$capsule = new Capsule;
$capsule->addConnection(
array(
'driver' => 'pgsql',
'host' => 'localhost',
'database' => 'database01',
'username' => 'postgres',
'password' => 'password',
'charset' => 'utf8',
'collation' => 'utf8_unicode_ci',
'prefix' => ''
)
);
$capsule->bootEloquent();
我该如何添加第二个数据库? (我看到一个不同的database.php文件配置,以“返回数组(...”开头)但我不知道如何用于Capsule或其他方式)
谢谢!
我遇到了同样的问题,我花了一段时间才在另一个论坛找到答案。
这就是我最终做的事情
<?php
use Illuminate\Database\Capsule\Manager as Capsule;
//connection to first database
$capsule = new Capsule;
$capsule->addConnection([
'driver' => $app->config->get('db.driver'),
'host' => $app->config->get('db.host'),
'database' => $app->config->get('db.name'),
'username' => $app->config->get('db.username'),
'password' => $app->config->get('db.password'),
'charset' => $app->config->get('db.charset'),
'collation' => $app->config->get('db.collation'),
'prefix' => $app->config->get('db.prefix'),
], 'default'); //the important line
// connection to second database
$capsule->addConnection([
'driver' => $app->config->get('db2.driver'),
'host' => $app->config->get('db2.host'),
'database' => $app->config->get('db2.name'),
'username' => $app->config->get('db2.username'),
'password' => $app->config->get('db2.password'),
'charset' => $app->config->get('db2.charset'),
'collation' => $app->config->get('db2.collation'),
'prefix' => $app->config->get('db2.prefix'),
], 'secondary_db'); // the important line
$capsule->setAsGlobal();
$capsule->bootEloquent();
不要过多考虑这种语法:$ app-> config-> get('db2.driver')。 我只是从另一个文件调用我的参数,就是这样。
你应该做的是看到我添加评论的“重要路线”
然后,您可以继续在二级模型上使用它,让Eloquent知道您确实想要使用辅助数据库
class Domains extends Eloquent
{
protected $connection = 'secondary_db';
.
.
.
您不需要使用默认数据库在模型中指定连接变量。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.