Yii Framework Forum: A Model With Two Different Database Connection - Yii Framework Forum

Jump to content

Page 1 of 1
  • You cannot start a new topic
  • You cannot reply to this topic

A Model With Two Different Database Connection Rate Topic: -----

#1 User is offline   Daniel 

  • Standard Member
  • PipPip
  • Yii
  • Group: Members
  • Posts: 213
  • Joined: 26-September 09

Posted 14 March 2013 - 11:26 PM

Hi,

I am having problem in handling requirements of my project. I have one table called transaction. However, it asked me to be able to store the transaction on 2 different database. If the code is 0 then, it will save on the first database, while if the code is 1, it should be stored on the second database.

Can we do this in yii?

Regards,

Daniel
0

#2 User is offline   yiiplayboy 

  • Junior Member
  • Pip
  • Yii
  • Group: Members
  • Posts: 56
  • Joined: 03-May 12

Posted 15 March 2013 - 04:25 AM

View PostDaniel, on 14 March 2013 - 11:26 PM, said:

Hi,

I am having problem in handling requirements of my project. I have one table called transaction. However, it asked me to be able to store the transaction on 2 different database. If the code is 0 then, it will save on the first database, while if the code is 1, it should be stored on the second database.

Can we do this in yii?

Regards,

Daniel


http://www.yiiframew...support-in-yii/
0

#3 User is offline   seenivasan 

  • Master Member
  • PipPipPipPip
  • Yii
  • Group: Members
  • Posts: 620
  • Joined: 17-June 12
  • Location:Chennai,TamilNadu,India.

Posted 15 March 2013 - 11:03 AM

Dear Friend

You can attach a behavior to main application.

In the behavior method we can create a new database connection , based on the condition.

main.php
........other properties....
'behaviors'=>array(
    'class'=>'application.components.applicationBehavior',
     ),

'components'=>array(

......other component declaration...

//DEFAULT CONNECTION...
		'db'=>array(
			'connectionString' => 'mysql:host=localhost;dbname=databaseRoutine',
			'emulatePrepare' => true,
			'username' => 'username',
			'password' => 'password',
			'charset' => 'utf8',
		),



components/applicationBehavior.php
class applicationBehavior extends CBehavior
{	private $_owner;
	
	public function events() 
       {
               return  array(
	               'onBeginRequest'=>'changeDb',        
		        );
       }
				
	public function changeDb()
        {
	    $owner=$this->_owner=$this->getOwner();
	    
            //PUT THE CONDITION HERE...
	    if($code===1)
            {
		$owner->db->setActive(FALSE);
		$owner->setComponent('db',new CDbConnection("mysql:host=localhost;dbname=newDatabaseName",'username','password'));
		$owner->db->setActive(TRUE);								
	    }
	}		
}
?>


I hope this will help you a bit.

Regards.
0

Share this topic:


Page 1 of 1
  • You cannot start a new topic
  • You cannot reply to this topic

1 User(s) are reading this topic
0 members, 1 guests, 0 anonymous users