tp5事务回滚操作多表

1.实现文章所属多个分类功能,文章表,分类表,文章和分类关联表,用tp5事务操作

$data获取的数据格式

array(5) {
  ["title"] => string(9) "水电费"
  ["art_desc"] => string(0) ""
  ["imageurl"] => string(0) ""
  ["views"] => string(0) ""
  ["category_id"] => array(2) {
    [0] => string(1) "3"
    [1] => string(1) "5"
  }
}

2.后台事务操作插入多表(文章表,文章和分类关联表)

 

public function RelaCateSave($data){
        // 多表 开启事务操作
        Db::startTrans();
        try{ 
            $res = model('article') -> save($data); 
            $art_id = model('article') -> getLastInsID(); //获得刚插入的id
            // 获取所属分类(数组集合)
            $category_id_arr = $data["category_id"];
            foreach ($category_id_arr as $key => $value) {
                $item = [
                    'art_id' => $art_id,
                    'category_id' => $value,
                ];
                $result = model('ArtRelaCate') -> insert($item); 
            }
            // 提交事务
            Db::commit();
        }catch(\Exception $e){
            // 回滚事务
            Db::rollback();
            dump($e->getMessage());
            return $this->error("提交失败");
        }
        return $this->success("提交成功",'article/index');
}

 

 

你可能感兴趣的:(tp5)