Yii PHP 框架中的多个数据库连接
Multiple db connections in Yii PHP framework
这是 main.php 文件:
'db' => array(
'connectionString' => 'mysql:host=MYHOST;dbname=MYDB',
'emulatePrepare' => true,
'username' => 'MYUSER',
'password' => 'MYPASS',
'charset' => 'utf8',
),
'dbanother' => array(
'connectionString' => 'mysql:host=MYHOST;dbname=MYDB2',
'emulatePrepare' => true,
'username' => 'MYUSER2',
'password' => 'MYPASS2',
'charset' => 'utf8',
'class' => 'CDbConnection'
),
在组件的 UserIdentity 中,我有这个:
public function authenticate() {
.........
$loggedInUser = User::model()->find("username = :username", array("username" => $this->username));
......
}
在 User 模型中,我想使用 MYDB2 数据库中的 table 用户:
class User extends CActiveRecord {
private $connection_db2;
/**
* @see db connections from config/main.php
*/
public function __construct(){
$this->connection_db2= Yii::app()->dbanother;
}
public static function model($className=__CLASS__){
return parent::model($className);
}
public function tableName() {
return Yii::app()->dbanother->users;
// here i want to declare That i want to use the table **users**
}
.....
}
目前我得到这个:
Property "CDbConnection.users" is not defined.
你能帮我解决这个问题吗?谢谢
它更简单 :) 只需重写 class:
中的 getDbConnection()
方法
public function getDbConnection() {
return Yii::app()->dbanother;
}
这是 main.php 文件:
'db' => array(
'connectionString' => 'mysql:host=MYHOST;dbname=MYDB',
'emulatePrepare' => true,
'username' => 'MYUSER',
'password' => 'MYPASS',
'charset' => 'utf8',
),
'dbanother' => array(
'connectionString' => 'mysql:host=MYHOST;dbname=MYDB2',
'emulatePrepare' => true,
'username' => 'MYUSER2',
'password' => 'MYPASS2',
'charset' => 'utf8',
'class' => 'CDbConnection'
),
在组件的 UserIdentity 中,我有这个:
public function authenticate() {
.........
$loggedInUser = User::model()->find("username = :username", array("username" => $this->username));
......
}
在 User 模型中,我想使用 MYDB2 数据库中的 table 用户:
class User extends CActiveRecord {
private $connection_db2;
/**
* @see db connections from config/main.php
*/
public function __construct(){
$this->connection_db2= Yii::app()->dbanother;
}
public static function model($className=__CLASS__){
return parent::model($className);
}
public function tableName() {
return Yii::app()->dbanother->users;
// here i want to declare That i want to use the table **users**
}
.....
}
目前我得到这个:
Property "CDbConnection.users" is not defined.
你能帮我解决这个问题吗?谢谢
它更简单 :) 只需重写 class:
中的getDbConnection()
方法
public function getDbConnection() {
return Yii::app()->dbanother;
}