本文介绍ThinkPHP5.0框架事务处理操作,结合实例形式分析了ThinkPHP5针对删除操作的事务处理相关操作技巧,可以加深对ThinkPHP源码的理解,需要的朋友可以参考下
事务的调用在mysql里需要注意下数据库引擎,处理前先查看一下
删除方法:
 1 public function del()
 2 {
 3     $cate = new CateModel;
 4     $id=input('id');
 5     $selectID=$cate->find($id);
 6     if($id == ''){
 7       $this->error('请不要恶意测试');
 8     }
 9     //调用事务删除
10     $del=$cate->shiwu($id);
11     if($del == true){
12       $this->success('删除成功/!');
13     }else{
14       $this->error('删除失败/!');
15     }
16 }
调用事务删除:
 1 //事务处理删除
 2 public function shiwu($id)
 3 {
 4   $cates=Cate::getChildId($id);
 5   Db::startTrans($id,$cates);  //$cates是所有子分类的一维数组
 6   try{
 7     Db::table('tp_cate')->where('id','in',$cates)->delete(); //删除所有子分类
 8     Db::table('tp_cate')->where('id',$id)->delete(); //删除自身
 9     // 提交事务
10     Db::commit();
11     return true;
12   } catch (\Exception $e) {
13     // 回滚事务
14     Db::rollback();
15     return false;
16   }
17 }
getChildId方法:
 1 public function getChildId($id)
 2 {
 3     $cateres=Cate::select();
 4     return $this->_getChildId($cateres,$id);
 5 }
 6 public function _getChildId($cateres,$id)
 7 {
 8     static $arr = array();
 9     foreach ($cateres as $k => $v) {
10       if($id == $v['pid']){
11         $arr[] = $v['id'];
12         $this->_getChildId($cateres,$v['id']);
13       }
14     }
15     return $arr;
16 }
完毕!不知道大家学会了没有?
 
  
  
  
 
 
  
 
 
 