如何在 Lumen 中使用多个数据库

How to use multiple database in Lumen

我们已经使用 Lumen 构建 API,现在我们需要访问多个数据库。

目前正在使用 .env 进行数据库配置,但无法在 .env 中找到多个数据库的路径

我们需要读取第二个连接...

首先,您需要配置连接。如果您还没有,则需要在项目中创建一个 config 目录并添加文件 config/database.php。它可能看起来像这样:

<?php

return [

   'default' => 'accounts',

   'connections' => [
        'mysql' => [
            'driver'    => 'mysql',
            'host'      => env('DB_HOST'),
            'port'      => env('DB_PORT'),
            'database'  => env('DB_DATABASE'),
            'username'  => env('DB_USERNAME'),
            'password'  => env('DB_PASSWORD'),
            'charset'   => 'utf8',
            'collation' => 'utf8_unicode_ci',
            'prefix'    => '',
            'strict'    => false,
         ],

        'mysql2' => [
            'driver'    => 'mysql',
            'host'      => env('DB2_HOST'),
            'port'      => env('DB_PORT'),
            'database'  => env('DB2_DATABASE'),
            'username'  => env('DB2_USERNAME'),
            'password'  => env('DB2_PASSWORD'),
            'charset'   => 'utf8',
            'collation' => 'utf8_unicode_ci',
            'prefix'    => '',
            'strict'    => false,
        ],
    ],
];

添加 connection 配置后,您可以通过从容器中取出数据库管理器对象并调用 ->connection('connection_name').

来访问它们
// Use default connection
app('db')->connection()->select('xx');
DB::connection()->select('yy');

// Use mysql2 connection
app('db')->connection('mysql2')->select('xx');
DB::connection('mysql2')->select('yy');

希望对你有帮助!!

这也奏效了。在当前版本的 Lumen 5.7

config/database.php

<?php

return [

    'default' => env('DB_CONNECTION', 'sqlsrv'),
    'migrations' => 'migrations',
    'connections' => [
        'sqlsrv' => [
            'driver' => 'sqlsrv',
            'host' => env('DB_HOST', 'localhost'),
            'port' => env('DB_PORT', '1433'),
            'database' => env('DB_DATABASE', 'forge'),
            'username' => env('DB_USERNAME', 'forge'),
            'password' => env('DB_PASSWORD', ''),
            'charset' => 'utf8',
            'prefix' => '',
            'prefix_indexes' => true,
        ],

        'sqlsrv2' => [
            'driver' => 'sqlsrv',
            'host' => env('DB_HOST', 'localhost'),
            'port' => env('DB_PORT', '1433'),
            'database' => env('DB_DATABASE2', 'forge'),
            'username' => env('DB_USERNAME', 'forge'),
            'password' => env('DB_PASSWORD', ''),
            'charset' => 'utf8',
            'prefix' => '',
            'prefix_indexes' => true,
        ],
    ],
];

.env

DB_CONNECTION=sqlsrv
DB_HOST=localhost
DB_PORT=1433
DB_DATABASE=database1
DB_USERNAME=username
DB_PASSWORD=password

DB_DATABASE2=database2

用法:

型号:protected $connection = 'sqlsrv2'; 其他:->connection('sqlsrv2')

希望能帮到你!

参考:https://fideloper.com/laravel-multiple-database-connections