Transaction.php 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. <?php
  2. namespace common\components;
  3. use Yii;
  4. use yii\base\Component;
  5. use yii\db\Transaction as DbTransaction;
  6. class Transaction extends Component{
  7. /**
  8. * 开启一个事务,不嵌套,多次调用只在一个事务中,兼容mycat
  9. * @Author bing
  10. * @DateTime 2021-10-14 10:59:56
  11. * @copyright: Copyright (c) 2020 广东七件事集团
  12. * @return DbTransaction
  13. */
  14. public $dirver;//数据库【mycat mysql】
  15. private $level=0;
  16. private $transaction;
  17. public function start(){
  18. if($this->dirver == 'mysql') return Yii::$app->db->beginTransaction();
  19. $this->transaction = Yii::$app->db->getTransaction();
  20. if($this->transaction){
  21. $this->transaction = Yii::$app->db->beginTransaction();
  22. }
  23. $this->level ++;
  24. return $this;
  25. // $level = Yii::$app->db->getTransaction()->getLevel();
  26. }
  27. public function rollback(){
  28. $this->level --;
  29. if($this->level === 0){
  30. $this->transaction->rollback();
  31. return;
  32. }
  33. }
  34. public function commit(){
  35. $this->level --;
  36. if($this->level === 0){
  37. $this->transaction->commit();
  38. }
  39. }
  40. public function getLevel(){
  41. $this->transaction->commit();
  42. return $this->level;
  43. }
  44. }