yii2 多数据库 事务 跨数据库事务

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/terry_water/article/details/49613535

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会回滚!



展开阅读全文

没有更多推荐了,返回首页