我可以看到如何使用app/config/database.php
中的配置文件建立多个连接,这已经有详细记录。
这是唯一的方法,还是可以使用.env文件定义多个连接?
答案 0 :(得分:3)
首先,您需要配置连接。您需要在项目中创建一个config目录并添加文件config / database.php。像这样:
<?php
namespace App\Http\Controllers;
use Illuminate\Database\DatabaseManager;
class StatsController extends Controller
{
/**
* @return array
*/
public function getLatest()
{
// Resolve dependencies out of container
/** @var DatabaseManager $db */
$db = app('db');
$database1 = $db->connection('mysql');
$database2 = $db->connection('mysql2');
// Look up 3 newest users and 3 newest blog posts
$threeNewestUsers = $database1->select("SELECT * FROM users ORDER BY created_at DESC LIMIT 3");
$threeLatestPosts = $database2->select("SELECT * FROM blog_posts ORDER BY created_at DESC LIMIT 3");
return [
"new_users" => $threeNewestUsers,
"new_posts" => $threeLatestPosts,
];
}
}
添加连接配置后,可以通过将数据库管理器对象从容器中取出并调用 - &gt; connection('connection_name')来访问它们。请参阅下面的完整示例。
{{1}}
http://andyfleming.com/configuring-multiple-database-connections-in-lumen-without-facades/