在一些业务开发业务需求中,项目数据支撑由多个数据库(Postgresql)组成,业务要求从DB-1获取Table A-User,将数据计算后批量插入DB-1的Table B-UserInfo以及之后删除Table A-User的数据,Table B中的业务数据营业需要删除的场景:
DB-1连接配置如下,db.php
'shop' => [
'class' => 'yii\db\Connection',
'dsn' => 'pgsql:host=192.168.xx;dbname=shop;port=9543',
'username' => 'shop',
'password' => '123456',
'charset' => 'utf8',
'enableSchemaCache' => false,
'enableProfiling' => true,
'schemaCacheDuration' => 0,
'schemaCache' => 'cache',
'tablePrefix' => 't_',
],
'manage' => [
'class' => 'yii\db\Connection',
'dsn' => 'pgsql:host=192.168.88.88;dbname=manage;port=9543',
'username' => 'manage',
'password' => '123456',
'charset' => 'utf8',
'enableSchemaCache' => false,
'schemaCacheDuration' => 0,
'schemaCache' => 'cache',
'tablePrefix' => 'm_',
],
大概实现流程如下:
................
$tran = Yii::$app->shop->beginTransaction();
$manageTran = Yii::$app->manage->beginTransaction();
try {
$user = user::find()
->where(['=', 'phone', $phone])
->asArray()->one();
$user = $this->formatUser($data);
$model = new User();
$model->setAttributes($sysUserInfo);
if (!$model->save()) {
throw new Exception($model->getMessage());
}
$data = [
'user_id' => $model->id,
................
];
$manage = new ManageUser();
$manage ->setScenario('add');
$manage ->setAttributes($data);
if (!$manage ->validate()) {
throw new Exception($manage ->getMessage());
}
$tran->commit();
$oauthTran->commit();
................
} catch (Exception $e) {
$tran->rollBack();
$manageTran->rollBack();
throw new Exception($e ->getMessage());
................
}
大致的结构及时这样的。
如果嵌套多层的话,比如内部某个方法里面有DB-1的事务,那么也是这样一层层事务提交/回滚。