【问题标题】:switching database php activerecord切换数据库php activerecord
【发布时间】:2012-12-27 12:53:41
【问题描述】:

我正在使用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' 是默认值。但不起作用。

【问题讨论】:

  • 你得到什么样的错误?
  • 没有错误。问题是即使 $current_db 取任何值,数据库也不会改变。
  • 您在此处发布的代码看起来不错,它一定是别的东西(在别处设置连接,$_SESSION['db'] 中的某些值等)
  • 首先,做一些调试。回显您的$current_db,例如在各个地方确认它实际上是“2”。然后,检查它是否适用于另一个默认值(test1)。此外,除了 activerecord 之外,还要测试您的连接。然后回到这里并显示结果:)
  • 我添加了print_r($_SESSION);,但如果我添加行print_r(Array(123, 55, 66)) 显示Array ( [0] => 123 [1] => 55 [2] => 66 ),什么都不显示(?!?!?!)为什么?

标签: php activerecord phpactiverecord


【解决方案1】:

我一般用这样的方法;

$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();

【讨论】:

  • 我的 ActiveRecord 抛出异常说 reestablish_connection() 没有定义。
【解决方案2】:

我找到了一个链接,里面有一个很好的切换数据库的解决方案here

编辑: 我在我的模型中定义了一个名为 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 关键字。我认为这是更好的主意。

【讨论】:

  • 请注意,您应该在此处或此站点上发布有用的答案点,否则您的帖子可能会被删除为"Not an Answer"。如果您愿意,您仍然可以包含该链接,但仅作为“参考”。答案应该是独立的,不需要链接。
猜你喜欢
  • 2014-08-28
  • 1970-01-01
  • 2011-12-27
  • 1970-01-01
  • 2010-09-20
  • 2021-12-31
  • 1970-01-01
  • 2010-09-23
  • 2019-03-10
相关资源
最近更新 更多