Laravel 的多数据库连接

在 app/config/database.php  中可以设置

<?php
return array(
    'default' => 'mysql',
    'connections' => array(
        # Our primary database connection
        'mysql' => array(
            'driver'    => 'mysql',
            'host'      => 'host1',
            'database'  => 'database1',
            'username'  => 'user1',
            'password'  => 'pass1'
            'charset'   => 'utf8',
            'collation' => 'utf8_unicode_ci',
            'prefix'    => '',
        ),

        # Our secondary database connection
        'mysql2' => array(
            'driver'    => 'mysql',
            'host'      => 'host2',
            'database'  => 'database2',
            'username'  => 'user2',
            'password'  => 'pass2'
            'charset'   => 'utf8',
            'collation' => 'utf8_unicode_ci',
            'prefix'    => '',
        ),
    ),
);

在 controller 中指定数据库

Schema::connection('mysql2')->create('some_table', function($table)
{
    $table->increments('id'):
});
$users = DB::connection('mysql2')->select(...);
<?php
class SomeModel extends Eloquent {
    protected $connection = 'mysql2';
}
<?php
class SomeController extends BaseController {
    public function someMethod()
    {
        $someModel = new SomeModel;
        $someModel->setConnection('mysql2');
        $something = $someModel->find(1);
        return $something;
    }
}

具体有时间再翻译

via: http://fideloper.com/laravel-multiple-database-connections

发表评论

Close Menu