【问题标题】:Laravel - Change Database Connection for a specific URL?Laravel - 更改特定 URL 的数据库连接?
【发布时间】:2014-11-11 12:17:43
【问题描述】:

我对使用 laravel 框架相当陌生。我有以下要求。我有一个域 - example.com,它的整个代码堆栈都在 laravel 中运行。假设在配置默认数据库连接是 - 'db1'

现在,如果 url 变为 -example.com/country - 我希望默认数据库连接变为 - 'db2'

我还希望将基本 URL 更改为 example.com/country,因为所有模块都将是相同的。这里只有数据库连接会发生变化。

有人可以帮我吗?

【问题讨论】:

    标签: php laravel laravel-4 laravel-routing


    【解决方案1】:

    我使用环境制作了类似的东西。

    在检测环境时添加新规则来解析URL并将其更改为新环境。然后,您可以为新环境添加一个目录,在其中设置新数据库、基本 URL 等。

    【讨论】:

    • 能否简单介绍一下如何操作?对不起,我不知道如何使用环境。
    • 一个代码示例可能很有用。
    【解决方案2】:

    我会这样做:

    将允许的国家列表放入配置文件 (countries.php)。

    routes.php:

    // choosing country
    $country = '';
    
    if (in_array(Request::segment(1), Config::get('countries'))) {
    
        $country = Request::segment(1);
    }
    
    // making route for top level 
    if ($country != '') {
        Route::any( '/', 'MainPage@index');
    }
    
    // making routes optionally prefixed by country 
    Route::group(
        array('prefix' => $country,
        function () {
           // here all routes
         });
    

    在您定义连接的database.php 中,您可以添加另一个连接,例如:

    'germany' => array(
        'driver'    => 'mysql',
        'host'      => 'localhost',
        'database'  => 'germany_connection',
        'username'  => 'root',
        'password'  => '',
        'charset'   => 'utf8',
        'collation' => 'utf8_unicode_ci',
        'prefix'    => '',
    ),
    

    现在在同一个文件中(尽管您可能应该将它移到其他地方)您可以这样做:

    if ($country == 'germany') {
        DB::disconnect();
        Config::set('database.default','germany');
        DB::reconnect();
    }
    

    您当然可以在这里添加许多条件,或者如果您为每个允许的国家/地区定义了连接,您可以简单地这样做:

    if ($country != '' ) {
        DB::disconnect();
        Config::set('database.default', $country);
        DB::reconnect();
    }
    

    应该可以,但是我没有测试过

    【讨论】:

      猜你喜欢
      • 2017-12-26
      • 2018-07-27
      • 2013-09-29
      • 2015-05-13
      • 2021-09-11
      • 2010-11-04
      • 1970-01-01
      • 2022-06-25
      • 1970-01-01
      相关资源
      最近更新 更多