rsanchez / Deep

A set of Eloquent models for ExpressionEngine Channel Entries.
http://rsanchez.github.io/Deep/
MIT License
51 stars 14 forks source link

Switching Database Connection #12

Closed cchiles closed 10 years ago

cchiles commented 10 years ago

Hi Rob,

I'm using this to grab content from EE to output in a Laravel app. I'm trying to figure out the best way to change the database connection to the EE db, but I'm not having any success. I'm pretty new to Laravel, so I may be missing something obvious. What's the best way to do this?

Thanks,

Chris

rsanchez commented 10 years ago

Since Deep is a collection of intertwined models, you'll have to change the DB connection at a global level, and then change it back (if you need to).

So let's say your database.php looks like this (reduced for clarity's sake):

<?php
return array(
    'default' => 'laravel',
    'connections' => array(
        'laravel' => array(
            'driver'    => 'mysql',
            'host'      => 'localhost',
            'database'  => 'laravel',
            'username'  => 'root',
            'password'  => 'root',
            'charset'   => 'utf8',
            'collation' => 'utf8_unicode_ci',
            'prefix'    => '',
        ),
        'ee' => array(
            'driver'    => 'mysql',
            'host'      => 'localhost',
            'database'  => 'ee',
            'username'  => 'root',
            'password'  => 'root',
            'charset'   => 'utf8',
            'collation' => 'utf8_unicode_ci',
            'prefix'    => 'exp_',
        ),
    ),
);

You'd need to something like this in your controller or route callback:

<?php
$connectionResolver = \Illuminate\Database\Eloquent\Model::getConnectionResolver();

// use the EE database
$connectionResolver->setDefaultConnection('ee');

$entries = Entries::get();

// switch back to the default database
$connectionResolver->setDefaultConnection('laravel');
cchiles commented 10 years ago

Thanks Rob!