1. 程式人生 > >yii2 多資料庫 事務 跨資料庫事務

yii2 多資料庫 事務 跨資料庫事務

1.配置:元件配置,db是預設的資料庫庫連線

 'components' => [
        'db' => [
            'class' => 'yii\db\Connection',
            'dsn' => 'mysql:host=localhost;dbname=erp',
            'username' => 'root',
            'password' => 'onfancy',
            'charset' => 'utf8',
			//'tablePrefix' => 'tbl_',   資料表字首
        ],
		
		
		'ebayDb' => [
            'class' => 'yii\db\Connection',
            'dsn' => 'mysql:host=localhost;dbname=erp_ebay',
            'username' => 'root',
            'password' => 'onfancy',
            'charset' => 'utf8', 
        ],

配置完成後,建立資料庫  erp  erp_ebay

然後建立表:

erp.test

erp_ebay.test

2.建立activeRecord 

namespace myapp\code\core\Erp\Sales\models;
use yii\db\ActiveRecord;

class Erptest extends ActiveRecord
{
	public static function tableName()
        {
          return 'test';
       }
}
上面的程式碼,getDb預設使用db的配置

<?php

namespace myapp\code\core\Erp\Sales\models;
use yii\db\ActiveRecord;

class Ebaytest extends ActiveRecord
{
	public static function getDb()
    {
        return \Yii::$app->ebayDb;  // use the "db2" application component
    }
	
	public static function tableName()
    {
        return 'test';
    }
}
上面的程式碼:通過getDb獲取上面配置的ebayDb的配置

然後就可以使用使用了

$innerTransaction = Yii::$app->db->beginTransaction();
		try {
			
			$erp_test = new Erptest();
			$erp_test->class = 99;
			$erp_test->age = 99;
			$erp_test->live = 99;
			$erp_test->save();
			
			$Ebaytest = new Ebaytest();
			$Ebaytest->age = 88;
			$Ebaytest->name = 88;
			$Ebaytest->live = 99;
			$Ebaytest->save();
			
			
			
			$data = Ebaytest::find()->asArray()->all();
			foreach($data as $d){
				var_dump($d);
			}
			
			
			$data = Erptest::find()->asArray()->all();
			foreach($data as $d){
				var_dump($d);
			}
			
			
		
			$innerTransaction->commit();
		} catch (Exception $e) {
			$innerTransaction->rollBack();
		}


當第二條插入執行失敗,mysql會回滾!