YII中的SaaS应用程序结构使用单独的数据库

时间:2013-06-11 14:03:42

标签: yii

我需要使用单独的数据库在YII Framework中创建SaaS应用程序结构,但Web中的示例使用单个数据库。欢迎任何信息或手册。

由于

1 个答案:

答案 0 :(得分:0)

您可以将第二个数据库添加到main.php例如:

    'db'=>array(
        'connectionString' => 'mysql:host=localhost;dbname=database',
        'emulatePrepare' => true,
        'username' => 'username',
        'password' => 'password',
        'charset' => 'utf8',
        'schemaCachingDuration' => 3600,
        'enableProfiling' => true,
    ),

    'db2'=>array(
        'connectionString' => 'mysql:host=localhost;dbname=database2',
        'class'=>'CDbConnection',
        'emulatePrepare' => true,
        'username' => 'username',
        'password' => 'password',
        'charset' => 'utf8',
        'schemaCachingDuration' => 3600,
        'enableProfiling' => true,
    ),

然后,您可以在要使用此第二个db的活动记录中设置getDbConnection()方法。我建议使用此代码从CActiveRecord扩展父类,然后扩展它。

它应该包含:

public static $db2;

public function getDbConnection()
{
  if(self::$db2!==null)
     return self::$db2;
  else
  {
     self::$db2=Yii::app()->db2;
     if(self::$db2 instanceof CDbConnection)
     {
        self::$db2->setActive(true);
        return self::$db2;
     }
     else
        throw new CDbException(Yii::t('yii','Active Record requires a "db" CDbConnection application component.'));
  }
}