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