Yii2如何进行多库配置和操作?

已邀请:

zkbhj - 凯冰科技站长

赞同来自:

1、配置文件中配置多个数据库信息:
'components' => [
'db' => [
'class' => 'yiidbConnection',
'dsn' => 'mysql:host=ip;dbname=dbname',
'username' => 'username',
'password' => 'pwd',
'charset' => 'utf8',
],
'db2' => [
'class' => 'yiidbConnection',
'dsn' => 'mysql:host=ip;dbname=dbname2',
'username' => 'username',
'password' => 'pwd',
'charset' => 'utf8',
],
],

2、建立模型Model,在model中加入下面的static方法:
public static function getDb() {
return Yii::$app->db2;
}

3、在要使用的位置:
use common\models\modelName;

$model = new modelName();

//验证
$model->setAttributes($data);
$model->validate()

//查询
$list = $model->findOne(['id'=>$data["id"]]);

//更新
$updateModel = $model->findOne(['id'=>$data["id"]]);
$updateModel->key = $value;
$updateModel->save();

//插入
$model->setAttributes($data);
$result = $model->save();

zkbhj - 凯冰科技站长

赞同来自:

另外一种方式
 
1、配置文件:配置文件web.php
'components' => [
'db' => require(__DIR__ . '/db.php'),
'db1' => require(__DIR__ . '/db1.php'),
]

2,db,db1配置 -- 可以根据需要将db.php db1.php 合并
db配置
return [
'class' => 'yii\db\Connection',
'dsn' => 'mysql:host=localhost;dbname=db', --数据库db
'username' => 'root',
'password' => 'test',
'charset' => 'utf8',
'tablePrefix'=>'db_'
];

db1配置
return [
'class' => 'yii\db\Connection',
'dsn' => 'mysql:host=localhost;dbname=db1', -- 数据库db1
'username' => 'root',
'password' => 'test',
'charset' => 'utf8',
'tablePrefix'=>'db1_'
];

3,查询
1,
Yii::$app->db->createCommand('select * from db.tableName')->queryAll();
Yii::$app->db1->createCommand('select * from db1.tableName')->queryAll();
2,
$db1 = Yii::$app->db1;
$query=(new \yii\db\Query())->select(['id','name'])->where('id=1')->from('add_log');
$data = $query->all($db1);------这里写的是Yii::$app->db1;
print_r($data);die;

要回复问题请先登录注册