ThinkPHP5使用模型对象开启事务,回滚无效

浏览:5484 发布日期:2018/03/31 分类:求助交流
public function create ($indentModel, $onlineIds)
    {
        $result = null;
        $indentModel->indent_num = $this->buildIndentOn();
        $indentModel->settle_account = 1; // 默认为未支付
        $indentModel->status = 1; // 显示为正常状态
        $indentModel->startTrans(); // 开启事务
        try {
            $result = $indentModel->save($indentModel->toArray());
            // 生成关联表数据
            $indentModel->indentMappings()->saveAll($onlineIds);
            $indentModel->commit(); // 提交事务
        } catch (\Exception $e) {
            $indentModel->rollback(); // 事务回滚
        }
        return $result;
    }
生成关联表的数据报错,异常块能捕获并执行代码。但是主表的数据还是新增成功了。感觉这样回滚失效了。
后来我试了一下Db方式。发现也是失效。 public function create ($indentModel, $onlineIds)
    {
        $indentModel->indent_num = $this->buildIndentOn();
        $indentModel->settle_account = 1; // 默认为未支付
        $indentModel->status = 1; // 显示为正常状态
        Db::startTrans();
        // $indentModel->startTrans(); // 开启事务
        try {
            $indentId = Db::table('indent')->insertGetId($indentModel->toArray());
            // $result = $indentModel->save($indentModel->toArray());
            // 生成关联表数据
            // $indentModel->indentMappings()->saveAll($onlineIds);
            for ($i = 0; $i < count($onlineIds); $i ++) {
                $onlineIds[$i]["indent_id"] = $indentId;
            }
            Db::table('indent_mapping')->insertAll($onlineIds);
            // $indentModel->commit(); // 提交事务
            Db::commit();
        } catch (\Exception $e) {
            // $indentModel->rollback(); // 事务回滚
            Db::rollback();
            return null;
        }
        return $indentModel;
    }
mysql数据使用的是innodb 我用SHOW variables like 'have_%';命令查询出来的结果是
have_compress YES
have_crypt NO
have_csv YES
have_dynamic_loading YES
have_geometry YES
have_innodb YES
have_ndbcluster NO
have_openssl DISABLED
have_partitioning YES
have_profiling YES
have_query_cache YES
have_rtree_keys YES
have_ssl DISABLED
have_symlink YES

这让我很尴尬。不知道问题出在哪。
请各位大神帮忙看看是原因导致。
最佳答案
评论( 相关
后面还有条评论,点击查看>>