CREATE TABLE afu.`test2` (
  `id` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
  `name` VARCHAR(50) DEFAULT '',
  PRIMARY KEY (`id`)
) ENGINE=INNODB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci
CREATE TABLE trade.`test2` (
  `id` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
  `name` VARCHAR(50) DEFAULT '',
  PRIMARY KEY (`id`)
) ENGINE=INNODB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci
<?php
/**
 * Created by PhpStorm.
 * User: cuzn
 * Date: 2018/12/28
 * Time: 19:10
 */


namespace app\afu\cron\department;

use app\afu\api\model\afu\Test2Model;
use app\afu\api\model\trade\Test1Model;
use PhpOffice\PhpSpreadsheet\Exception;

require_once __DIR__ . '/../../conf/config.inc.php';

echo "exec at " . date('Y-m-d H:i:s') . "\n";


$Test1Model = Test1Model::getInstance();


function addTest2($isBack = false){
    $Test2Model = Test2Model::getInstance();
    try {
        $Test2Model->begin();
    
        $ret = $Test2Model->insert([
            'name' => 'bbbbbbb'
        ]);
        if (!$isBack) {
            $Test2Model->commit();
            return true;
        } else {
            $Test2Model->rollback();
            return false;
        }
    } catch (Exception $e) {
        $Test2Model->rollback();
        throw $e;
        //return false;
    }
}


try {
    $Test1Model->begin();
    
    $ret = $Test1Model->insert([
        'name' => 'aaaaaa'
    ]);
    $ret2 = addTest2(false);
    var_dump($ret, $ret2);
    if ($ret && $ret2) {
        $Test1Model->commit();
    }else {
        $Test1Model->rollback();
    }
} catch (Exception $e) {
    //addTest2(1);
    $Test1Model->rollback();
    throw $e;
}

 

 

 function x1()
  {
    $x1 = db1("x1", 1);
    $x2 = db2("x2");
    $x1->startTrans();
    try {
      $x1->find();
      $ret1 = $x1->where(['id' => 1])->update(['title' => "x1_11"]);
      if($ret1){
        $x2->startTrans();
        try {
          $x2->find();
          $ret2 = $x2->where(['id' => 1])->update(['title' => "x1_111"]);
          if ($ret1 && $ret2) {
            dump(1);
            $x1->commit();
            $x2->commit();
          }else{
            dump(2);
            $x1->rollback();
            $x2->rollback();
          }
        } catch (\Exception $e) {
          // 回滚事务
          dump(3);
          $x1->rollback();
          $x2->rollback();
          echo "x2 : " . $e->getMessage();
        }
      }else{
        dump(4);
        $x1->rollback();
      }
    } catch (\Exception $e) {
      // 回滚事务
      dump(5);
      $x1->rollback();
      echo "x1 : " . $e->getMessage();
    }
  }

声明:此文系舞林cuznwww.wulinlw.org)原创稿件,转载请保留版权

et_highlighter