1

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?

MarBer
  • 535
  • 1
  • 5
  • 22

1 Answers1

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();
ScaisEdge
  • 131,976
  • 10
  • 91
  • 107
  • Thanks, the second way is better for my purpose, only one question more: after some googling about my problem I found the model `getDb()` function (related at this question [link to question](https://stackoverflow.com/questions/27254540/multiple-database-connections-and-yii-2-0) ), but if I have set a db component in module configuration how I can access to this component from a model, more generic in a model of a module how I can access to module instance? If I use the name of module in configuration the name have to be always the same name (the module born to be shared on multiple sites) – MarBer Jul 20 '17 at 06:15
  • You can access to a componet with `Yii::$app->your_compenent_name` .. and you can access to the param as key - value array (or as an obbject .. I don't remember now)) .. but pratically is the same as is in myModuleDbCon .. just change the place where you assign the param .. – ScaisEdge Jul 20 '17 at 06:18