如何为2 db连接生成SqlDataProvider

时间:2016-06-09 03:03:23

标签: yii2 yii2-basic-app

我有一个2 DB连接,db和db2。我想从db2连接中的表声明中获取所有数据。下面是我的sql,它没有从db2连接读取。怎么解决这个问题?

$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;

1 个答案:

答案 0 :(得分: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()

如果您使用的是活动记录模型,则可以在模型中定义:

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

//或db2

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

然后:

如果在getDb()方法中设置了db1,则将从db1中获取结果,依此类推。

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