问题
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' is default. But does not work.
回答1:
I generally use a method like this;
$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();
回答2:
I found a link with an excellent solution for switching databases here
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;
}
If you see in the link, note that I added the static
keyword. I think that is better idea.
来源:https://stackoverflow.com/questions/14055067/switching-database-php-activerecord