How To Create Relations With Multiple Databses Connections

[i][b]Hi All

I Created multiple connection for tow databases just for test this feature in Yii ,




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

			'emulatePrepare' => true,

			'username' => 'root',

			'password' => '',

			'charset' => 'utf8',




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

			'emulatePrepare' => true,

			'username' => 'root',

			'password' => '',

			'charset' => 'utf8',

         	'class'        	=> 'CDbConnection'  




[u]in single database I use for relations this code :

For Example [/u][/color]

	public function relations()


		// NOTE: you may need to adjust the relation name and the related

		// class name for the relations automatically generated below.

		return array(

			'user' => array(self::BELONGS_TO, 'Users', 'user_id'),

			'section' => array(self::BELONGS_TO, 'Sections', 'section_id'),

			'editby0' => array(self::BELONGS_TO, 'Users', 'editby'),

			'topstories' => array(self::HAS_MANY, 'Topstory', 'article_id'),





So if table ([color="#FF0000"]y[/color]) in database [[color="#FF8C00"]B[/color]] have relation with table ([color="#FF0000"]x[/color]) in database [[color="#FF8C00"]A[/color]] .

How To write Relations and how to call it ?

thanks in advance [/b]

Make sure you’ve followed all of the steps in this wiki. Specifically, you need to make sure you override getDbConnection().

thanks Keith , I read that before I wrote this post and every things is work with me but my question is :

If I had relations between tow tables in different connections , is possible to make relation ???

I suspect that the relations will work as long as they are lazily loaded. This is assuming that the two active record classes have been assigned different connections. I’m not sure what will happen if you attempt to load eagerly, but it’s worth trying to see what happens.

You may be able to avoid this problem completely, by just using one connection and changing the tableName() method in each model class to include the database name:

	public function tableName()


		return 'database.table';


I don’t know if this will work, but it might be worth trying. If it does work, it’ll allow you to join eagerly as well as lazily. It also assumes that you’re happy to give access to both databases to a single account.

I tested this solution and this works.

Thanks for your idea.