簡體   English   中英

沒有Laravel的Eloquent ORM中的兩個數據庫

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM