2015-04-23 45 views
0

我想要動態更改數據庫連接,我成功使用了codeigniter 2.2.0,但未使用3.0版本。Codeigniter 3.0 - 無法動態更改數據庫連接

這裏是我的代碼:

public function index(){ 
     $this->load->model('compte_model','compte'); 
     $this->load->model('utilisateur_model','utilisateur'); 
     $this->load->helper('database_helper'); 

     //Getting the database where to connect from the principale database 
     $compte = $this->compte->get_by('nom',$this->input->get('nom')); 
     $bdd = $compte->bdd_principale; 

     //Get the new configuration 
     $newDBB = getGroupName($bdd); 
     $this->load->database($newDBB,TRUE); 

     //Made a query in the second database but it doesn't work 
     $users = $this->utilisateur->get_all(); 

     return $users; 
    } 

這裏的輔助函數:

function getGroupName($bdd){ 
    $config['hostname'] = "localhost"; 
    $config['username'] = "root"; 
    $config['password'] = ""; 
    $config['database'] = $bdd; 
    $config['dbdriver'] = "mysql"; 
    $config['dbprefix'] = ""; 
    $config['pconnect'] = TRUE; 
    $config['db_debug'] = TRUE; 
    $config['cache_on'] = FALSE; 
    $config['cachedir'] = ""; 
    $config['char_set'] = "utf8"; 
    $config['dbcollat'] = "utf8_general_ci";  

    return $config; 
} 
+2

是的,因爲您仍然在使用$ this-> db的任何地方都會引用原始數據庫連接...我強烈建議您閱讀http://www.codeigniter.com上的用戶指南/user_guide/database/connecting.html – TimBrownlaw

回答

1

一些測試後,我已經找到了解決辦法:

  • 首先,模型在第二個數據庫中必須在更改數據庫配置後加載 。
  • 其次,我們必須發送數據庫的參數,爲 返回FALSE,併爲query_builder返回TRUE。

最後,該代碼將是這樣的:

public function index_get(){ 
     $this->load->model('compte_model','compte'); 
     $this->load->helper('database_helper'); 

     $compte = $this->compte->get_by('nom',$this->input->get('nom')); 
     $bdd = $compte->bdd_principale; 

     //Get the new configuration 
     $newDBB = getGroupName($bdd); 
     $this->load->database($newDBB,FALSE,TRUE); 

     $this->load->model('utilisateur_model','utilisateur'); 

     $users = $this->utilisateur->get_all(); 

     return $users; 
    } 

發送此參數應用的原因是爲了改變「$這個 - > DB」實例。