0

我正在使用ActiveRecord,我需要切换数据库。当我登录时,我选择了一个数据库。数据库是相同的模式。我试过了:

$connections = array(
   '1' => 'mysql://root:pass@localhost/db1;charset=utf8',
   '2' => 'mysql://root:pass@localhost/db2;charset=utf8',
   'test' => 'mysql://root:password@localhost/database_name'
 );

 $current_db = $_SESSION['db'] ?  $_SESSION['db'] : '2';


 ActiveRecord\Config::initialize(function($cfg) use ($connections, $current_db)
 {
   $cfg->set_model_directory(MODEL_PATH);
   $cfg->set_connections($connections);

   $cfg->set_default_connection($current_db);
 });

db '2' 是默认值。但不起作用。

4

2 回答 2

0

我在这里找到了一个链接,其中包含用于切换数据库的出色解决方案

编辑switch_connection:我定义了一个在我的模型中调用的方法

   public static function switch_connection($name) {

     $cfg = ActiveRecord\Config::instance();    
     $valid = $cfg->get_connections();
     if ( ! isset($valid[$name])) {
       throw new ActiveRecord\DatabaseException('Invalid connection specified');
     }

     // Get the name of the current connection
     $old = self::$connection;

     $cm = ActiveRecord\ConnectionManager::instance();
     $conn = $cm::get_connection($name);
     static::table()->conn = $conn;

     return $old;
   }

如果您在链接中看到,请注意我添加了static关键字。我认为这是更好的主意。

于 2013-01-30T20:01:47.903 回答
0

我一般使用这样的方法;

$all = new SomeModel(); // class of ActiveRecord\Model
$all->table()->class->setStaticPropertyValue("connection","test"); //test - defined in cfg
$all->table()->reestablish_connection();
//then use it as usual.
$all_data = $all->all();
于 2013-01-22T14:13:00.813 回答