I don't know if it sounds stupid or duplicated question. But I'm trying to move to multiple databases in my project. Each company should have a particular database. And each company should have different type of users (I mean users who have different roles). All databases have same structure but different data. Is this possible to jump to another database? If it is, how?
1 Answer
Are possible several ways
a way is based on different db componente declaration in you confing
return [
'components' => [
'db_default' => [
'class' => 'yii\db\Connection',
'dsn' => 'mysql:host=localhost;dbname=mydb_default',
'username' => 'my_username_default',
'password' => 'my_password_default',
],
'db1' => [
'class' => 'yii\db\Connection',
'dsn' => 'mysql:host=localhost;dbname=mydb1',
'username' => 'my_username1',
'password' => 'my_password1',
],
'db2' => [
'class' => 'yii\db\Connection',
'dsn' => 'mysql:host=localhost;dbname=mydb2',
'username' => 'my_username2',
'password' => 'my_password2',
],
....
],
];
then you can extend all your Class redefining the getDb function
class Customer extends ActiveRecord
{
// ...
public static function getDb()
{
// you could check some application condition for get the db you need
// use the "db2" application component
switch ($my_condition) {
case 'condition_1':
return \Yii::$app->db1;
break;
case 'condition_2':
return \Yii::$app->db2;
break;
default:
return \Yii::$app->db_default;
break;
}
}
}
another way is create the connection to db dinamically
if (isset(Yii::$app->db)){
Yii::$app->db->close()
}
Yii::$app->db= \yii\db\Connection([
// dsn user and password are from session, set these value during login procedure
'dsn' => 'mysql:host=localhost;dbname=your_act_dbname',
'username' => 'your_act_username',
'password' => 'your_act_password,
]);
$models = Yii::$app->db->createCommand('SELECT * FROM your_table')
->queryAll();
In $models you should have all the models of the table selected from the database assigned in Connection You can check the contents of $models eg: using var_dump($models)
10 Comments
Scott
Do me a little favor man. Describe how to change dynamically??
ScaisEdge
when you need to connect another database you can close() the open connectio and create a new one .. yiiframework.com/doc-2.0/yii-db-connection.html yiiframework.com/doc-2.0/guide-db-dao.html
Scott
I'm doing this:
echo Yii::$app->db->dsn; $db = Yii::$app->db; $db->close(); $db->dsn = 'mysql:host=localhost;dbname=sherik'; $db->username = 'root'; $db->password = '123'; $db->charset = 'utf8'; $db->open(); But still not working. What am I doing wrong???Scott
What do you mean?
ScaisEdge
i have added the code for a connection and the use the connection for select from a table and get the result in $models .. hope is clear ..
|