Laravel 4 - Connect to other database

后端 未结 6 2239
暖寄归人
暖寄归人 2020-12-08 01:25

I want to connect to another database sometimes.

I created a config.php with the database connection data.

But how can i tell laravel to connect to this data

6条回答
  •  没有蜡笔的小新
    2020-12-08 01:48

    Remember that Laravel 4 is actually a collection of components, and you can use these components solo.

    https://github.com/illuminate/database

    There is an example here that shows off how interacting with the Capsule class works:

    use Illuminate\Database\Capsule\Manager as Capsule;
    
    $capsule = new Capsule;
    
    $capsule->addConnection([
        'driver'    => 'mysql',
        'host'      => 'localhost',
        'database'  => 'database',
        'username'  => 'root',
        'password'  => 'password',
        'charset'   => 'utf8',
        'collation' => 'utf8_unicode_ci',
        'prefix'    => '',
    ]);
    
    // Set the event dispatcher used by Eloquent models... (optional)
    use Illuminate\Events\Dispatcher;
    use Illuminate\Container\Container;
    $capsule->setEventDispatcher(new Dispatcher(new Container));
    
    // Set the cache manager instance used by connections... (optional)
    $capsule->setCacheManager(...);
    
    // Make this Capsule instance available globally via static methods... (optional)
    $capsule->setAsGlobal();
    
    // Setup the Eloquent ORM... (optional; unless you've used setEventDispatcher())
    $capsule->bootEloquent();
    

    This is a bunch of bootstrapping that you'll need to run, so tuck it away somewhere in a function or method.

    But, its absolutely possible.

提交回复
热议问题