multiple database connections

Hi ,

I am working with a MySQL and MSSQL databases, I can connect to each succesfully if the connection details are put in the ‘db’ section of the config file, but is there a way to set the db connection to different settings on a model by model basis?

I notice the db property in the docs but setting this in my model causes the script to fail.

http://www.yiiframework.com/doc/api/CActiveRecord#db-detail




class AUser extends CActiveRecord

{

	var $db = 'mssql';

	

	public static function model($className=__CLASS__)

	{

		return parent::model($className);

	}



See getDbConnection():




class AUser extends CActiveRecord

{


   public function getDbConnection()

   {

      return Yii::app()->db2;

   }


}



excellent thank you!

Does anyone know how to specify the database connection in the yiic shell? It doesn’t know where to find my db.

I hope you have found the answer to this by now, but just in case you haven’t - here goes.

Once you’ve extracted the yii package, and you have created a webapp through the shell, you’ll need to edit the config in protected/config/main.php and enter the database connection details in the relevent section ( I think the default SQLite connection will be in there - you want to replace this).

For example:




return array(

  ...

  'components'=>array(

    ...

    'db'=>array(

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

      'username' => 'myuser',

      'password' => 'mypass',

    ),

    ...

  ),

  ...

);



Then when you use the shell according to the install instructions, it will be talking to your database, instead of the default SQLite DB, and you can create models, CRUD controllers etc at will.

Of course, if you are using Yii 1.1.2 then once the DB connection has been configured you can use gii instead of the shell to generate your code.

Thank you, but I was talking about using it with multiple databases. Its true that you can change the config every time you work with a different database, but that is a bit of a pain.

I didn’t know about gii, however, or that 1.1.2 was out. I’ll check it out.

Thanks.