【问题标题】:Lumen connecting to multiple databases using DB_ connections in .env - Possible?Lumen 使用 .env 中的 DB_ 连接连接到多个数据库 - 可能吗?
【发布时间】:2016-01-27 14:07:48
【问题描述】:

我可以看到如何使用app/config/database.php 中的配置文件进行多个连接,这有据可查。

这是唯一的方法,还是您也可以使用 .env 文件定义多个连接?

【问题讨论】:

  • 感谢您提供详细而清晰的回复。这就是我已经按照文档对多数据库问题进行编码的方式。缺少的关键位仍然是“您还可以使用 .env 文件定义多个连接吗?”

标签: lumen


【解决方案1】:

首先,您需要配置连接。您需要在项目中创建一个配置目录并添加文件 config/database.php。像这样:

<?php
return [

    'default' => 'mysql',
    'connections' => [
        'mysql' => [
            'driver'    => 'mysql',
            'host'      => 'localhost',
            'database'  => 'homestead',
            'username'  => 'root',
            'password'  => 'secret',
            'charset'   => 'utf8',
            'collation' => 'utf8_unicode_ci',
            'prefix'    => '',
            'strict'    => false,
        ],
        'mysql2' => [
            'driver'    => 'mysql',
            'host'      => 'localhost',
            'database'  => 'homestead2',
            'username'  => 'root',
            'password'  => 'secret',
            'charset'   => 'utf8',
            'collation' => 'utf8_unicode_ci',
            'prefix'    => '',
            'strict'    => false,
        ],
    ],

添加连接配置后,您可以通过从容器中取出数据库管理器对象并调用 ->connection('connection_name') 来访问它们。请参阅下面的完整示例。

<?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,
        ];
    }
}

http://andyfleming.com/configuring-multiple-database-connections-in-lumen-without-facades/

【讨论】:

猜你喜欢
  • 2018-05-09
  • 1970-01-01
  • 2021-04-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-03-04
  • 1970-01-01
  • 2021-12-09
相关资源
最近更新 更多