Long story short,
[color="#0000FF"]I need a dynamic connection to separate DB’s for multiple tenants[/color]
I modified my model for when the constructor() is given a $tenantID, it will search within his DB.
class TENANT_Page extends CActiveRecord
{
public $tenantID = null;
/* Overridden */
public function __construct( $scenario = 'insert', $tenantID = null )
{
if ( $tenantID != null)
{
$this->tenantID = $tenantID;
}
parent::__construct($scenario);
}
/* Overridden */
public function getDbConnection()
{
return Yii::app()->dynamicDB->getTenantConnection($this->tenantID);
}
This is my custom component to manage all my connections to all DB’s.
class DynamicDB extends CApplicationComponent
{
public $connection;
public $externalTenant;
public function getDbConnection($IPaddress,$dbName, $username, $password)
{
$this->connection=new CDbConnection('mysql:host='.$IPaddress.';dbname='.$dbName, $username, $password);
$this->connection->active=true;
return $this->connection;
}
public function getTenantConnection($tenantID = null)
{
if ($tenantID == null){
return Yii::app()->tenant->db;
} else {
$this->externalTenant = GTBtenant::model()->findByPk($tenantID);
if ($this->externalTenant == null){
Yii::app()->alert->sendAlert(Alert::ERROR_ALERT, 'the tenant ('.$tenantID.') couldnt be found, when requested by class ['.__CLASS__.']');
} else {
return $this->getDbConnection( $this->externalTenant->IPaddress,
$this->externalTenant->DBname,
$this->externalTenant->username,
$this->externalTenant->password );
}
}
}
}
[color="#0000FF"]Now the usage of all this![/color]
[color="#FF0000"]THIS DOESN’T WORK!!![/color]
$newPage = new TENANT_Page(null, $_GET['tenantID'] );
$newPage->attributes=$_POST['TENANT_Page'];
if ($newPage->validate()){
$newPage->save(false);
} else {
Yii::app()->alert->sendAlert(Alert::ERROR_ALERT_IGNORE, 'When trying to create a page and error occured!');
}
[color="#00FF00"]THIS WORKS!!![/color]
$newPage = new TENANT_Page(null, $_GET['tenantID'] );
$newPage->attributes=$_POST['TENANT_Page'];
if ($newPage->validate()){
$newPage->saveCustom();
} else {
Yii::app()->alert->sendAlert(Alert::ERROR_ALERT_IGNORE, 'When trying to create a page and error occured!');
}
[color="#00FF00"]—>WITH THIS UGLY HACK [/color]
class TENANT_Page extends CActiveRecord
{
[...]
public function saveCustom(){
$table=tableName(); //
$val=$this->pageName.','.$this->pageTitle.','.$this->IDtemplate;
$dns=$this->getDbConnection()->connectionString;
$connection=new CDbConnection( $dns,'username','password');
$connection->active=true;
yii::app()->toolbox->alert('dddd');
$sql="INSERT INTO $table (pageName, pageTitle,IDtemplate) VALUES($val)";
$command=$connection->createCommand($sql);
$command->query();
$connection->active=false;
/* */return true;
}
Why the save(false) method doesn’t work!? I tried to crack this problem for a while now… All this is pretty straight forward…