我正在使用 Yii-1.1.13。我有两个数据库,我都在protected/config/main.php
下面进行了配置。
'db2'=>array(
'class' => 'CDbConnection' ,
'connectionString' => 'pgsql:host=localhost;port=5432;dbname=database2',
'emulatePrepare' => true,
'username' => 'zzzzz',
'password' => 'zzzzz',
'charset' => 'utf8',
),
'db'=>array(
'connectionString' => 'pgsql:host=localhost;port=5432;dbname=database1',
'emulatePrepare' => true,
'username' => 'xxxxx',
'password' => 'xxxxx',
'charset' => 'utf8',
),
我正在使用下面的代码来显示Yii CGridView中的计数,它工作正常。这将连接database1。
楷模
<?
public function search()
{
$criteria=new CDbCriteria;
$criteria->select='std_id ,count(*) as counts';
$criteria->condition = "sdate between '$this->startdate' and '$this->enddate'";
$criteria->group ='std_id';
return new CActiveDataProvider($this, array(
'criteria'=>$criteria,
'pagination' => array( 'pageSize' => 30 ),
));
}
?>
看法
<?php $this->widget('zii.widgets.grid.CGridView', array(
'id'=>'std_id-grid',
'dataProvider'=>$model->search(),
'columns'=>array(
'std_id',
'counts',
),
)); ?>
在另一个模型中,我有以下代码来显示将与 database2 连接的用户详细信息。它不起作用,那有什么问题。我尝试了两种不同的方法。请参见下面的 Type-1 和 Type-2。
我已经参考了这个链接来连接 Yii 中的多个数据库。
楷模
<?
class Usr extends SecDB
{
...
..
public function getDbConnection()
{
return self::getSecDbConnection();
//We need to override this method in the models representing the
//advertising database to return the second DB connection.
}
public function search()
{
// Type -1 Not working
/*$row = Yii::app()->db2->createCommand(array(
'select' => array('id', 'name', 'date_created'),
'from' => 'accounts',
'where' => "type = 'USERS'",
))->queryAll();
return new CActiveDataProvider($this, array(
'criteria'=>$row,
));
*/
// Type -2 Not working
$criteria=new CDbCriteria;
$criteria->select='id,name,date_created';
$criteria->condition = "type = 'USERS'";
return new CActiveDataProvider($this, array(
'criteria'=>$criteria,
));
}
?>
}
看法
<?php $this->widget('zii.widgets.grid.CGridView', array(
'id'=>'users-grid',
'dataProvider'=>$model->search(),
'columns'=>array(
'id',
'name',
'date_created'
),
)); ?>
我已经覆盖了数据库连接。但它不起作用,浏览器中没有任何内容。
我SecDB.php
在 protected/components/SecDB.php
<?php
class SecDB extends CActiveRecord {
private static $db2 = null;
public static function getSecDbConnection()
{
if (self::$db2 !== null){
return self::$db2;
}else
{
self::$dbcc = Yii::app()->db2;
if (self::$db2 instanceof CDbConnection)
{
self::$db2->setActive(true);
return self::$db2;
}
else
throw new CDbException(Yii::t('yii','Active Record requires a "db2" CDbConnection application component.'));
}
}
}
?>