【问题标题】:Using an extended Kohana DB class for multiple databases with ORM使用 ORM 为多个数据库使用扩展的 Kohana DB 类
【发布时间】:2011-11-30 22:33:15
【问题描述】:

在我正在进行的当前项目中,数据分布在两个数据库中。我们尝试使用的方法是为第二个数据库使用别名,然后扩展数据库类以将别名替换为实际的数据库名称。

在 /classes/database/mysql.php 中,我们添加了这个:

class Database_MySQL extends Kohana_Database_MySQL {
    public static $alias;
    public static $sprtDbName;

    public function __construct($name, $config) {
        $con = $config['connection'];
        self::$sprtDbName = "$con[database]_support";
        parent::__construct($name, $config);
    }

    public function query($type, $sql, $as_object = FALSE, array $params = NULL) {
        $sql = str_ireplace('SUPPORT_ALIAS', self::$sprtDbName, $sql);
        return parent::query($type, $sql, $as_object, $params);
    }
}

在 /config/database.php 中,我们有这个:

$db_config = array(
    'dev_local' => array(
        'type'      => 'mysql',
        'connection' => array(
            'hostname'  => 'localhost',
            'username'  => 'username',
            'password'  => 'password',
            'database'  => 'db_name'
        ),
        'table_prefix' => '',
        'charset'      => 'utf8',
        'caching'      => FALSE,
        'profiling'    => TRUE,
    ),
    'support' => array(
        'type'      => 'mysql',
        'connection' => array(
            'hostname'  => 'localhost',
            'username'  => 'username',
            'password'  => 'password',
            'database'  => 'SUPPORT_ALIAS'
        ),
        'table_prefix' => '',
        'charset'      => 'utf8',
        'caching'      => FALSE,
        'profiling'    => TRUE,
    ),
);

问题是:在我的一个 ORM 课程中,当我像这样开始课程时,它工作正常:

class Model_Something extends ORM {
    protected $_table_name = 'SUPPORT_ALIAS.something';
    public $doc_id = null;
    public $document_compiled = null;

但是当我使用这个方法时:

class Model_Something extends ORM {
    protected $_table_name = 'something';
    public $doc_id = null;
    public $document_compiled = null;
    protected $_db = 'support';

我收到此错误:

Database_Exception [ 1044 ]: Access denied for user 'username'@'localhost' to database 'SUPPORT_ALIAS'

别名永远不会被替换。我错过了什么?

【问题讨论】:

    标签: php mysql database orm kohana


    【解决方案1】:

    我本身无法真正回答您的问题,但我会使用 Kohana 对非标准数据库的内置支持:

    http://kohanaframework.org/3.2/guide/orm/models#use-a-non-default-database

    所以,而不是:

    protected $_db = 'support';
    

    用途:

    protected $_db_group = 'support';
    

    因此,不需要class Database_MySQL extends Kohana_Database_MySQL

    希望这会有所帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-05-11
      相关资源
      最近更新 更多