Home  >  Article  >  php教程  >  Yii ExtendedActiveRecord 增强版 ActiveRecord 增加多数据库连接绑定功能,activerecord

Yii ExtendedActiveRecord 增强版 ActiveRecord 增加多数据库连接绑定功能,activerecord

WBOY
WBOYOriginal
2016-06-13 09:27:311067browse

Yii ExtendedActiveRecord 增强版 ActiveRecord 增加多数据库连接绑定功能,activerecord

ExtendedActiveRecord 继承自 CActiveRecord,因此基础功能与 CActiveRecord 无异

为添加对多数据库连接的支持,增加了对 connectionName() 方法的回调,用法跟已有的 tableName() 方法一致,返回数据库连接组件名称的字符串。

如果不定义该方法,则使用默认数据库连接(db)

源码如下:

class ExtendedActiveRecord extends CActiveRecord
{
    public static $db = array();

    /**
     * @return CDbConnection
     * @throws CDbException
     */
    public function getDbConnection()
    {
        $componentName = $this->connectionName();
        if (isset(self::$db[$componentName])) {
            return self::$db[$componentName];
        } else {
            self::$db[$componentName] = Yii::app()->getComponent($componentName);
            if (self::$db[$componentName] instanceof CDbConnection)
                return self::$db[$componentName];
            else {
                $message = 'Active Record keyword requires a "' . $componentName . '" CDbConnection application component.';
                Yii::log($message, CLogger::LEVEL_ERROR, 'extended');
                throw new CDbException(Yii::t('yii', $message));
            }
        }
    }

    public function connectionName()
    {
        return 'db';
    }
}

 

实例:

class SomeModelClass extends ExtendedActiveRecord
{
    ......

    public function connectionName() {
        return 'some-db-connection';
    }

    ......
}

  

 

Ralis连接远程数据库,提示ActiveRecord::ConnectionNotEstablished ,本地pl/sql可以访问远程数据库

你是局域网内可以远程连接,广域网使用外网ip不可以连接吗?
路由器上要映射ip地址和数据库端口
 

yii20怎与XAMPP的数据库连接?

yii2.0 官方提供两个模板
先说基本版:
只要修改 config/db.php
return [
'class' => 'yii\db\Connection',
'dsn' => 'mysql:host=localhost;dbname=yii2',
'username' => 'root',
'password' => '',
'charset' => 'utf8',
'tablePrefix' => 'hpcms_',
];

其中dbname是指数据库名、 host 是主机、 tablePrefix 是表前缀

高级版的也差不多,修改 common/config/main-local.php
配置参数和上述基本一致!

这样就可以链接数据库了(当然你得要启动mysql才可以,如果是其他数据库,请搜索一下,基本都是配置下参数即可)

对于如何操作数据库(增删改查)请看文档ActiveRecord 以及Model (设计表结构后,可以用Gii快速生成Model)

想知道更多的话,看文档最实际
 

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn