How To Change Databases(Db And Db2) Automatically In One Model?

Hi,everyone.

How To Change Databases(Db And Db2) Automatically In One Model?

In config.php,I have set two db,db and db2.

config.php




'db'=>array(			

'connectionString' => 'mysql:host=localhost;dbname=aa_1',			

'emulatePrepare' => true,			

'username' => 'root',			

'password' => '',			

'charset' => 'utf8',),		


'db2'=>array(			

'class'=>'CDbConnection',			

'connectionString' => 'mysql:host=localhost;dbname=aa_2',			

'emulatePrepare' => true,			

'username' => 'root',			

'password' => '',			

'charset' => 'utf8',),



model Users.php




<?php 

class Users extends CActiveRecord {

......	

public function getDbConnection(){		

if(Yii::app()->db !== null)			

return Yii::app()->db;		

else{			

if(Yii::app()->db2 instanceof CDbConnection){				

Yii::app()->db2->setActive(true);				

return Yii::app()->db2;			

}else				

throw new CDbException(Yii::t('yii','...'));}}//overwritted the function getDbConnection

......

}



views admin.php




<strong>Choose server</strong>	

<select name="server" id="server">	

<option value="aa1">aa1 Server</option>	

<option value="aa2">aa2 Server</option></select>



How do the page jump to the right server automatically when I choose aa1 Server or aa2 Server?

Some one say I can write a controller function to control which database to choose ,how?

Thank you very much!

Dear life_free

I hope the following will serve the purpose.

1.Create a controller action and view to choose the database.

view-serverAllot




<?php

echo CHtml::beginForm();

echo CHtml::dropDownList('server','server1',array('server1'=>'adminServer','server2'=>'normalServer'));

echo CHtml::submitButton('submit');

echo CHtml::endForm();

?>

<div style="margin-top:10px;font-size:16px;">

<?php

if(Yii::app()->user->hasState('server')) { 

	if(Yii::app()->user->getState('server')=='adminServer')

		echo "You are currently using admin server";

        elseif(Yii::app()->user->getState('server')=='routineServer')

		echo "You are currently using routine server";

    

		}

?>

</div>



action




public function actionServerAdmin() 

{

	    if(isset($_POST['server'])) 

              {

		     if($_POST['server']=='server1')

				Yii::app()->user->setState('server','adminServer');

	              elseif($_POST['server']=='server2')

				Yii::app()->user->setState('server','routineServer');

	      }

	        

		$this->render('serverAllot');                    

}



By making it into persistant state, we can work across many requests and controllers.

2.Create an application behavior and attach it to main application.

applicationBehavior.php in components directory




<?php

class applicationBehavior extends CBehavior

{        private $_owner;

	 public function events() {


                        return  array(

			        'onBeginRequest'=>'changeDb',        

		        );

                                   }

	

	public function changeDb(){

	  $owner=$this->_owner=$this->getOwner();

		

		if($owner->user->hasState('server') && $owner->user->getState('server')=='adminServer')

		    {

			$owner->db->setActive(FALSE);


                        //admin-the new database.

			$owner->setComponent('db',new CDbConnection("mysql:host=localhost;dbname=admin",'root','yourpassword'));

			$owner->db->setActive(TRUE);

				

				}

		}

	

	}

?>



Attach this behavior instance as a property to main configuration file. Leave the ‘db’ component intact.

main.php




return array(

......................................

.......................................

'behaviors'=>array(

'class'=>'application.components.applicationBehavior',

),

......................................

......................................

'components'=>array(

.........................................

........................................

'db'=>array(

			'connectionString' => 'mysql:host=localhost;dbname=routine',//rotine-default database

			'emulatePrepare' => true,

			'username' => 'root',

			'password' => 'password',

			'charset' => 'utf8',

		),

.....................................................

....................................................

),

)



You can create new models by creating new tables in the database(admin) for exclusive use in admin pages.

If you want to share already created models, your new tables should exactly simulate the tables in routine data

base. Ofcoures you can easily import and export tables.

Regards.

Thank you very much , seenivasan.You help me a lot !

The code is so awesome!

But there is something you have ignored. That is you have forgotten to use the action ServerAdmin() in the controllor,the form in the view does not have an url to use it.

I modify the code like this.

views admin.php




<select name="server" id="server" onchange="return chooseServer();">

		<option value="empty" selected>choose server</option>

		<option value="aa1">aa1 Server</option>

		<option value="aa2">aa2 Server</option>	

	</select><br><br>

function chooseServer(){

	var server = document.getElementById('server').value;	

	<?php		

	echo CHtml::ajax(

	array(

		"url" => CController::createUrl("Users/ServerAdmin"),

		"data" => "js:{servers : server}", 

		"type"=>"POST",

	)

);

	?>

}




action




public function actionServerAdmin() 

{

            if(isset($_POST['servers'])) 

              {

                     if($_POST['servers']=='server1')

                                Yii::app()->user->setState('server','adminServer');

                      elseif($_POST['servers']=='server2')

                                Yii::app()->user->setState('server','routineServer');

              }

                

                $this->render('serverAllot');                    

}



Thank for your share again ,seenivasan.