We want to build a multi-tenant application with multiple databases. Does YII support this out of the box, if not then, Is there any packages available to do this?

We want to build a multi-tenant application with multiple databases.
Does YII support this out of the box, if not then, Is there any packages available to do this?

'components' => [
    'db' => [
        'class' => \yii\db\Connection::class,
        'dsn' => 'mysql:host=localhost;dbname=db1',
        'username' => 'root',
        'password' => '123',
        'charset' => 'utf8',
    ],
    
    'db_remote2' => [
        'class' => \yii\db\Connection::class,
        'dsn' => 'mysql:host=localhost;dbname=db2',
        'username' => 'root',
        'password' => '456',
        'charset' => 'utf8',
    ],  

    'db_remote3' => [
        'class' => \yii\db\Connection::class,
        'dsn' => 'mysql:host=localhost;dbname=db3',
        'username' => 'root',
        'password' => '789',
        'charset' => 'utf8',
    ],
1 Like

How application decide which db connection needs to be set, if a new tenant is created then for this a separate db will be created, then how this automatically decide for db connection, Is there any package available for this?

You can compose new db connections programmatically, for example say you store the db configuration of each tenant in their settings page:

$db = new yii\db\Connection([
    'dsn' => 'mysql:host=localhost;dbname=tenant_database',
    'username' => 'root', 
    'password' => '',
    'charset' => 'utf8',
]);