多个数据库连接和 Yii 2.0 [英] Multiple database connections and Yii 2.0
本文介绍了多个数据库连接和 Yii 2.0的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有两个数据库,每个数据库都有相同的表和相同的字段,但是如何在 Yii 2.0?
I have two databases, and every database has the same table with the same fields, but how do I get all records from all of two databases at the same time in Yii 2.0?
推荐答案
首先你需要像下面这样配置你的数据库:
First you need to configure your databases like below:
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 (PostgreSQL),...
'username' => 'db2username',
'password' => 'db2password',
],
],
];
然后你可以简单地:
// To get from db1
Yii::$app->db1->createCommand((new \yii\db\Query)->select('*')->from('tbl_name'))->queryAll()
// To get from db2
Yii::$app->db2->createCommand((new \yii\db\Query)->select('*')->from('tbl_name'))->queryAll()
如果您使用的是活动记录模型,您可以在模型中定义:
If you are using an active record model, in your model you can define:
public static function getDb() {
return Yii::$app->db1;
}
//Or db2
public static function getDb() {
return Yii::$app->db2;
}
那么:
如果你在getDb()
方法中设置了db1
,结果将从db1
中获取,依此类推.
If you have set db1
in the getDb()
method, the result will be fetched from db1
and so on.
ModelName::find()->select('*')->all();
这篇关于多个数据库连接和 Yii 2.0的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文