How i can force an yii2 module to use a specific connection for all his models?

这一生的挚爱 提交于 2020-01-05 07:04:15

问题


on a module I have add a component named db where i put, like the main Yii component, the data for database connection, I need in my module use everytime the db specified in his configuration for all models and not the main database connection, how I can do this?


回答1:


You have several way eg. using a separated configuration in app/config/main.php eg adding a specific dbMyMod to component config

return [
// ...
'components' => [
    // ...
    'db' => [
        'class' => 'yii\db\Connection',
        'dsn' => 'mysql:host=localhost;dbname=example',
        'username' => 'root',
        'password' => '',
        'charset' => 'utf8',
    ],
    'dbMyMod ' => [
        'class' => 'yii\db\Connection',
        'dsn' => 'mysql:host=hostForMudle;dbname=module_db_name',
        'username' => 'user_module_name',
        'password' => 'password',
        'charset' => 'utf8',
    ],

],

or one way that not require a static configuration in app/confing

could be based on a module function that return a proper db connection

public function myModuleDbCon()
{
   $myDbCon = new yii\db\Connection([
           'dsn' => 'mysql:host=localhost;dbname=example',
           'username' => 'root',
           'password' => '',
           'charset' => 'utf8',
    ]);
    return myDbConn;

}

then in you module you can retrive the module db connection

aDbConn = Yii::$app->getModule('my_module_name')->myModuleClass->myModuleDbCon();

.

 $command = $aDbConn->createCommand('SELECT * FROM myTable');
 $result= $command->queryAll();


来源:https://stackoverflow.com/questions/45195007/how-i-can-force-an-yii2-module-to-use-a-specific-connection-for-all-his-models

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!