Laravel-全局更改默认数据库连接 [英] Laravel - change the default database connection globally

查看:554
本文介绍了Laravel-全局更改默认数据库连接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的database.php中,我配置了两个数据库.

In my database.php, I have TWO databases configured.

'db1' => array(
  'driver'   => 'pgsql',
  'host'     => 'localhost',
  'database' => 'db1',
  'username' => 'root',
  'password' => 'password',
  'charset'  => 'utf8',
  'prefix'   => '',
  'schema'   => 'public',
), 

'db2' => array(
  'driver'   => 'pgsql',
  'host'     => 'localhost',
  'database' => 'db2',
  'username' => 'root',
  'password' => 'password',
  'charset'  => 'utf8',
  'prefix'   => '',
  'schema'   => 'public',
),

因此,默认情况下,db1最初设置为默认数据库.现在,我想通过从选择"下拉列表中选择一个选项,将默认数据库切换为"db2".这将向我执行的控制器方法发出AJAX发布请求

So by default db1 is set as default DB initially. Now I want to switch the default database to 'db2' by selecting an option from 'select' dropdown. This will do a post AJAX request to the controller method in which I do

public function postChangeDb()  {
    $db = Input::get('db');
    Config::set('database.default', $db);
}

完成此操作后,我将刷新"页面,但连接仍位于"db1".

Once this is done, I 'refresh' the page, but the connection is still at 'db1'.

我还尝试了以下方法

  public function getTest() {
    Config::set('database.default', 'db1');
    $users = User::all();
    echo sizeof($users); // returns 20

    Config::set(database.default', 'db2');
    $users = User::all();
    echo sizeof($users); // returns 50 - which is correct!
  }

上面的方法工作正常,可以成功切换数据库.切换是否基于每个请求"?

And the above works fine and it successfully switches the database. Is the switch 'per request' basis?

推荐答案

Config::set仅在每个请求的基础上起作用,因此您可能想要在Session中设置数据库并获取它在随后的请求中.

Config::set is only going to work on a per-request basis, so you're probably going to want to set your database in the Session and grab it on subsequent requests.

您可以选择在何处执行此操作. /app/start/global是一种选择.在控制器中,构造器将是另一个.您也可以注册服务提供商来做到这一点.

You have some options on where to do that. /app/start/global would be one option. In the controller constructor would be another. You could register a service provider to do it, too.

下面是一个示例,该示例显示了控制器构造函数中的代码[警告:未经测试的代码!]:

Below is an example of what the code might look like [warning: untested code!] in the controller constructor:

   public function __construct() {
     if(Session::has('selected_database'){
        Config::set('database.default',Session::get('selected_database'));
     } else {
        return Redirect::to('database_choosing_page');
     }
   }

和数据库设置功能的更新:

and an update to your database setting function:

public function postChangeDb()  {
    $db = Input::get('db');
    Session::put('selected_database',$db);
    Config::set('database.default', $db);
}

这篇关于Laravel-全局更改默认数据库连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆