2017-06-08 81 views
0

在控制器中,我想更改默認數據庫,以便我可以從網站中的任何位置訪問新的數據庫(db2)。 db2數據庫具有相同的模型,但只是不同的數據。我的代碼只是訪問其他數據庫,但沒有將新的默認數據庫設置爲db2,可以在網站的任何地方訪問它。我沒有從下面的帖子中得到答案。在cakephp3中更改默認數據庫

//controller 
$connection = ConnectionManager::get('db2'); // 'db2' where my second database is configured 
    $results = $connection->execute('SELECT * FROM tutors')->fetchAll('assoc'); 
    //this works but doesnt set the default database to db2 everywhere 

//app.php 
'Datasources' => [ 
     'default' => [ 
      'className' => 'Cake\Database\Connection', 
      'driver' => 'Cake\Database\Driver\Mysql', 
      'persistent' => false, 
      'host' => 'localhost', 

      //'port' => 'non_standard_port_number', 
      'username' => 'root', 
      'password' => '', 
      'database' => 'aptutori_test', 
      'encoding' => 'utf8', 
      'timezone' => '+11:00', 
      'flags' => [], 
      'cacheMetadata' => true, 
      'log' => false, 


      'quoteIdentifiers' => false, 



      'url' => env('DATABASE_URL', null), 
     ], 
     'db2' => [ 
      'className' => 'Cake\Database\Connection', 
      'driver' => 'Cake\Database\Driver\Mysql', 
      'persistent' => false, 
      'host' => 'localhost', 

      //'port' => 'non_standard_port_number', 
      'username' => 'root', 
      'password' => '', 
      'database' => 'aptutori_testbak', 
      'encoding' => 'utf8', 
      'timezone' => '+11:00', 
      'flags' => [], 
      'cacheMetadata' => true, 
      'log' => false, 


      'quoteIdentifiers' => false, 



      'url' => env('DATABASE_URL', null), 
     ], 


https://stackoverflow.com/questions/30262176/dynamically-change-database-connection-in-cakephp-3 
http://mark-story.com/posts/view/using-cakephp-and-a-horizontally-sharded-database 

回答

2

使用ConnectionManager::alias()

http://api.cakephp.org/3.0/class-Cake.Datasource.ConnectionManager.html#_alias

富勒例如這將使那些需要default連接使用db2所有表:

ConnectionManager::alias('db2', 'default'); 
+0

我想這能爲每個控制器工作,所以我需要在全球範圍內設置。我的問題是數據庫(上面的代碼)只改變控制器功能,但我有大約30個控制器。 – jagguy

+0

如何在所有控制器/模型中全局設置此更改 – jagguy

+0

AppController類是所有應用程序控制器的父類 –

相關問題