laravel – 动态切换数据库连接

对于多个控制台命令,我需要更改数据库,以便所有有力的命令和查询在正确的数据库(和服务器)上运行.

我看到了几个解决方案,最简单的似乎是像这样改变配置:

$new_connection = [
        'driver'    => 'MysqL','host'      => '127.0.0.1','database'  => 'test_db','username'  => 'test','password'  => 'test','charset'   => 'utf8','collation' => 'utf8_general_ci','prefix'    => '','strict'    => false
];

config(['database.connections.MysqL' => $new_connection]);
DB::purge('MysqL');

唯一的问题(我注意到)是当我尝试做交易时,更具体地说,当我在Codeception中的验收测试中进行交易时,它们根本不起作用.

我使用的命令是:

DB::connection()->beginTransaction(); // inside the _before function

DB::connection()->rollBack(); // inside the _after function

解决方法

您必须创建2个不同的连接

http://fideloper.com/laravel-multiple-database-connections
https://laravel.com/docs/5.1/database#accessing-connections

return array(
    'default' => 'MysqL','connections' => array(

        # Our primary database connection
        'MysqL' => array(
          'driver'    => 'MysqL','strict'    => false
        ),# Our secondary database connection
        'MysqL2' => array(
          'driver'    => 'MysqL','database'  => 'test_db_2',),);

现在当你想查询你必须传递你需要的连接

$users = DB::connection('MysqL2')->select(...);

由于认值是声明为MysqL,因此您可以省略它.

相关文章

SELECT a.*,b.dp_name,c.pa_name,fm_name=(CASE WHEN a.fm_n...
if not exists(select name from syscolumns where name=&am...
select a.*,pano=a.pa_no,b.pa_name,f.dp_name,e.fw_state_n...
要在 SQL Server 2019 中设置定时自动重启,可以使用 Window...
您收到的错误消息表明数据库 'EastRiver' 的...
首先我需要查询出需要使用SQL Server Profiler跟踪的数据库标...