2012-12-27 36 views
0

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

$connections = array(
    '1' => 'mysql://root:[email protected]/db1;charset=utf8', 
    '2' => 'mysql://root:[email protected]/db2;charset=utf8', 
    'test' => 'mysql://root:[email protected]/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'是默认值。但不起作用。

+0

你会得到什么样的错误? –

+0

没有错误。问题是,即使$ current_db取任何值都不会改变数据库。 –

+1

你在这里发布的代码看起来不错,它必须是别的东西(设置其他地方的连接,某些值在$ _SESSION ['db']等) –

回答

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(); 
+0

我的ActiveRecord抛出异常,说reestablish_connection()没有定义。 –

0

我找到了一个很好的解决方案的链接交换数据库here

编辑: 我在我的模型

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; 
    } 

定义了一个名为switch_connection方法如果您在链接中看到请注意,我添加了static关键字。我认为这是个好主意。

+0

请注意,您应该在此处发布答案的有用观点,或将您的帖子风险删除为[“未回答”](http://meta.stackexchange.com/q/8259)。如果您愿意,您可能仍然包含链接,但仅作为“参考”。答案应该独立,不需要链接。 –