2017-02-11 96 views
0

我需要更改路由數據庫連接(前綴)更改數據庫連接, 當用戶路線site.com/db1/post系統中使用DB1組件的配置,並在路線site.com/db2/post使用的系統db2YII2。通過路由

'components' => [ 
'db1' => [ 
    ..., 
    'tablePrefix' => 'base1_', 
], 
'db2' => [ 
    ..., 
    'tablePrefix' => 'base2_', 
], 
... 

可以嗎? 也許有更好的解決辦法來改變分貝前綴。 我需要使用一個模型,不同的表(只前綴的變化)

回答

0

有幾個選項。可能最簡單的是使用url規則;看到http://www.yiiframework.com/doc-2.0/guide-runtime-routing.html#url-rules

rules => [ 
    '<db:db\d>/post' => 'site/post', 
] 

這將DB1 /後重定向到網站/後以及 「db」 參數設置爲 「DB1」。然後在您的SiteController:

public function actionPost($db) { 
    YourModel::setDb(Yii::$app->$db); 
    $model = new YourModel(); 
    // do what you need with your model 
    // and return the rendered result 
} 

在你的模型類,你需要重寫getDb()靜態方法,譜寫setDb方法:

private static $_db; 

public static function getDb() { 
    if (isset(self::$_db)) { 
     return self::$_db; 
    } 
    return ActiveRecord::getDb(); 
} 

public static function setDb($db) { 
    self::$_db = $db; 
} 
+0

感謝FOT答案! 我忘了,我有太多的控制器。 我通過改變用戶使用其他的方式,爲每個用戶做你的數據庫連接。 –

0

一個簡單的解決方案是在先進的模板..,你有不同的配置部分的兩個不同的應用程序類似。在

/db1/config/main.php 

你可以把設置好的訪問到你喜歡的表前綴的數據庫組件(或者還數據庫您喜歡)

'components' => [ 
    'db' => [ 
..., 
    'tablePrefix' => 'base1_', 
    ], 

/db2/config/main.php 

'components' => [ 
    'db' => [ 
..., 
    'tablePrefix' => 'base2_', 
    ], 

您可以使用常見的命名空間,所有你需要的常見應用elemnts ..模式,控制器,視圖等..上
和特定元素的每個命名空間有限公司Reseved ..

Obviuosly這isjust建議..可能是有其他人很容易和智能解決方案

PS:使用兩個獨立的數據庫,你並不需要不同的前綴..