我们使用Lumen构建API,现在我们需要访问多个数据库。
目前使用.env
进行数据库配置但无法找到.env
我们需要阅读第二个连接...
答案 0 :(得分:11)
首先,您需要配置连接。如果您还没有,则需要在项目中创建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');
希望这可以帮助你!!
答案 1 :(得分:0)
这也起作用。在当前版本的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