我正在使用Yii-1.1.13。我有兩個數據庫,我已經在protected/config/main.php
配置如下。Yii:在CGridView中顯示第二個數據庫內容
'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計數,其工作的罰款。這將連接數據庫1。
模式
<?
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。
我已經通過this鏈接來連接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'
),
)); ?>
我overwite數據庫連接。但它不工作,沒有什麼是在瀏覽器中。 感謝Advanse。
我在保護/組件SecDB.php
/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.'));
}
}
}
?>
閱讀本評論:http://www.yiiframework.com/wiki/123/multiple-database-support-in-yii/#c4816 – tinybyte