Two databases in bright ORM without Laravel

I'm using Eloquent ORM without Laravel, it works fine with one database, but I don't know how to use the second database. I am using Capsule to set up eloquent

DATABASE.PHP FILE:

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

      

how can i add a second database? (I see a different configuration in the database.php file that starts with "array returned (...", but I don't know how to use this for Capsule or otherwise)

thank!

+3


source to share


1 answer


I faced the same problem and it took me a while to find the answer in another forum.

that's what i finished doing

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

      

Don't think too much about this syntax: $ app-> config-> get ('db2.driver'). I just call my parameters from another file that's all.



What you need to do is see the "important line" to which I added a comment

then you can go ahead and use this on your secondary models to let Eloquent know that you really want to use the secondary database

class Domains extends Eloquent
{
    protected $connection = 'secondary_db';
    .
 .
.

      

you don't need to specify the connection variable in models using the default database.

0


source







All Articles