2016-06-09 46 views
0

我有2個DB連接,db和db2。我想從db2連接中的表索賠中獲取所有數據。下面是我的SQL,它沒有從db2連接讀取。如何解決這個問題?如何爲2 db連接生成SqlDataProvider

$sql = "SELECT * FROM claim where provider_id = xx "; 
$sql_count = "SELECT COUNT FROM ($sql) AS count "; 
$totalCount = Yii::$app->db2->createCommand($sql_count)->queryScalar(); 
$dataProvider = new SqlDataProvider([ 
'sql' => $sql, 
'totalCount' => $totalCount, 
'sort' =>false, 
'pagination' => [ 
     'pageSize' => 10, 
    ], 
]); 
return $dataProvider; 

回答

0

首先,你需要配置你的數據庫,如下面:

return [ 
'components' => [ 
    'db1' => [ 
     'class' => 'yii\db\Connection', 
     'dsn' => 'mysql:host=localhost;dbname=db1name', //maybe other dbms such as psql,... 
     'username' => 'db1username', 
     'password' => 'db1password', 
    ], 
    'db2' => [ 
     'class' => 'yii\db\Connection', 
     'dsn' => 'mysql:host=localhost;dbname=db2name', //maybe other dbms such as psql,... 
     'username' => 'db2username', 
     'password' => 'db2password', 
    ], 
], 
]; 

那麼你可以簡單:

//to get from db1 
Yii::$app->db1->createCommand((new \yii\db\Query)->select('*')->from('tbl_name'))->queryAll() 

//從DB2獲得

Yii::$app->db2->createCommand((new \yii\db\Query)->select('*')->from('tbl_name'))->queryAll() 

如果你在MOD中使用了一個活躍的記錄模型埃爾您可以定義:

public function getDb() { 
    return Yii::$app->db1; 
} 

//或DB2

public function getDb() { 
    return Yii::$app->db2; 
} 

然後:

如果您在getDb設置DB1()方法,因此將DB1中獲取等。

ModelName::find()->select('*')->all(); 
+0

我已經有了所有的配置。我之前提供的sql是在db2上的聲明模型上,而這個sql是從db連接上的另一個模型調用的。當我做print_r($ dataProvider)時,數據庫名稱不是來自db2的db連接。是因爲我從db連接上的模型調用函數? – kasmawati