Search code examples
databaseyii2prefix

YII2. Change db connection by routing


I need to change db connection (prefix) by routing, When user route to site.com/db1/post system used db1 components config, and when route to site.com/db2/post system used db2

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

Can it`s possible? Maybe have better solution to change db prefix. I need to use one model with different table (only prefix change)


Solution

  • There are a couple of options. Probably the easiest is using url rules; see http://www.yiiframework.com/doc-2.0/guide-runtime-routing.html#url-rules

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

    This will redirect db1/post to site/post with the "db" parameter set to "db1". Then in your 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
    }
    

    In your model class, you will need to override the getDb() static method, and write a setDb method:

    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;
    }