切换数据库php activerecord [英] switching database php activerecord

查看:112
本文介绍了切换数据库php activerecord的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 ActiveRecord ,并且我需要切换数据库.登录时,我选择一个数据库. 数据库是相同的架构. 我试过了:

I'm using ActiveRecord and I need switching databases. When I log-in I select a database. The databases are the same schema. I tried:

$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'是默认值.但是不起作用.

db '2' is default. But does not work.

推荐答案

我找到了一个很好的解决方案链接,用于切换数据库

I found a link with an excellent solution for switching databases here

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

EDIT: I define a method called switch_connection in my model

   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关键字.我认为这是个好主意.

If you see in the link, note that I added the static keyword. I think that is better idea.

这篇关于切换数据库php activerecord的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆