0
votes

I'm developing SaaS application using Yii2. I have a problem in setting db Connection. I'm using separate db structure for each Tenant. I have one login form with Tenant Company, username and password. Using company name I need to get database name, database username and database password which created for relevant tenant and establish db connection. Then need to validate login with entered username and password.

I tried as following example. https://forum.yiiframework.com/t/change-db-connection-dynamically/76412

But it sets the db connection after login, having validated the login from a common database connection. I need to validate connection from tenant database,

How I can get success output with above system requirements?

1

1 Answers

0
votes

I think you should call specific database as per the functionality So you need to configure multiple database in your yii

    you need to add database configuration in common/config/main-local.php 

    <?php
    return [
        'components' => [
            'db' => [
                'class' => 'yii\db\Connection',
                'dsn' => 'mysql:host=localhost;dbname= FIRST DATABASE NAME',
                'username' => USER NAME,
                'password' => PASSWORD,
                'charset' => 'utf8',
            ],
            'db1' => [
                'class' => 'yii\db\Connection',
                'dsn' => 'mysql:host=localhost;dbname= SECOND DATABASE NAME',
                'username' => USER NAME,
                'password' => PASSWORD,
                'charset' => 'utf8',
            ]
        ],
    ];

?>

   // code for your project's components file
    //use Yii; use this is your class file 

    // this is only for select query you can update for update ,delete and insert as well

    // $query : wrire your query like 'SELECT * from test'

    // $dbname : from which db you want to execute given query like (db OR db1)



    public function execute($query,$dbName)
    {
        $connection = Yii::$app->get($dbName);
        $command = $connection->createCommand($query);
        $response = $command->queryAll();
        return $response;
    }