问题
I am using PostgreSQL and the default database schema in my Yii2 application.
I created a new schema called laboratory and I need to define it in the common/config/main-local.php file.
This is my current main-local.php file:
<?php
return [
'components' => [
'db' => [
'class' => 'yii\db\Connection',
'dsn' => 'pgsql:host=localhost;dbname=travel',
'username' => 'aaaa',
'password' => 'bbbb',
'charset' => 'utf8',
],
],
];
How can I add the laboratory schema in this file? I need both schemas.
Is Yii2 supporting multiples schemas?
回答1:
You can configure more than one in components
return [
'components' => [
'db1' => [
'class' => 'yii\db\Connection',
'dsn' => 'mysql:host=localhost;dbname=testdb1',
'username' => 'demo1',
'password' => 'demo1',
],
'db2' => [
'class' => 'yii\db\Connection',
'dsn' => 'mysql:host=localhost;dbname=testdb2',
'username' => 'demo2',
'password' => 'demo2',
],
],
];
and you can refer to each one using
\Yii::$app->db1;
or
\Yii::$app->db2;
http://www.yiiframework.com/doc-2.0/guide-db-active-record.html
http://www.yiiframework.com/doc-2.0/guide-start-databases.html
for postgresql you could try
return [
'components' => [
'db1' => [
'class' => 'yii\db\Connection',
'dsn' => 'pgsql:host=localhost;dbname=testdb1',
'username' => 'demo1',
'password' => 'demo1',
'schemaMap' => [
'pgsql'=> [
'class'=>'yii\db\pgsql\Schema',
'defaultSchema' => 'your_schema1' //specify your schema here
]
],
],
'db2' => [
'class' => 'yii\db\Connection',
'dsn' => 'mysql:host=localhost;dbname=testdb2',
'username' => 'demo2',
'password' => 'demo2',
'schemaMap' => [
'pgsql'=> [
'class'=>'yii\db\pgsql\Schema',
'defaultSchema' => 'your_schema2' //specify your schema here
]
],
],
],
];
回答2:
It wasn't necessary to change it:
<?php
return [
'components' => [
'db' => [
'class' => 'yii\db\Connection',
'dsn' => 'pgsql:host=localhost;dbname=travel',
'username' => 'aaaa',
'password' => 'bbbb',
'charset' => 'utf8',
],
],
];
Then Gii code generator recognizes the laboratory schema (but autocomplete for Table Name doesn't work).
来源:https://stackoverflow.com/questions/47228767/yii2-how-to-specify-multiples-database-schemas