I have multiple clients (companies) and each client has multiple users.
Each client has their own database, so during user authentication, I discover the name of associated database for that user.
The structure of each database is identical… only the data is different.
The number of clients (and therefor the number of databases) is unknown when the application is written, so it is not possible to include all the connections in the bootstrap script.
Now, what I want to do is, dynamically alter the DB connection that is in the bootstrap or have the ability to dynamically create a new connection for the user signing in. Is there a simple solution for this in Yii and still use AR?
No, I never received a response. As a result, I decided to use a different framework (QCubed), where there are more users and assistance is more readily available.
You can override CActiveRecord::getDbConnection like the following:
public function getDbConnection()
{
if(self::$db!==null)
return self::$db;
else
{
// create DB connection based on your spec here:
// self::$db=new CDbConnection(...);
// self::$db->active=true;
// return self::$db;
}
}
Alll your AR classes should then extend this new base class.
abstract class NewDbConnection extends CActiveRecord
{
private $db_connection='db';
public function getDbConnection()
{
print "--->".$this->db_connection."<br>";
$db = Yii::app()->{$this->db_connection};
$db->setActive(true);
return $db;
}
public function setDbConnection($c)
{
$this->db_connection=$c;
print "X----->".$this->db_connection."<br>";
}
}
It works,
the only issue is that i have to initialize db_connection because getDbConnection is called at model creatin so it need to be a valid database connection that contains the table associated with the model.