tp中使用事务

是什么

事务是为了防止,多个操作,其中有失败,数据有部分被执行成功的时候使用的。

比如,银行,用户转账。张三钱扣了,结果李四钱还增加!

这个时候需要使用事务,确保张三钱扣了,李四的钱也增加,才真正的成功!

能干嘛

确保数据的一致性!

如何使用呢?

/**
     * 启动事务
     * @access public
     * @return void
     */
    public function startTrans() {
        $this->commit();
        $this->db->startTrans();
        return ;
    }

    /**
     * 提交事务
     * @access public
     * @return boolean
     */
    public function commit() {
        return $this->db->commit();
    }

    /**
     * 事务回滚
     * @access public
     * @return boolean
     */
    public function rollback() {
        return $this->db->rollback();
    }

使用任何的model对象都可以开启。

        // 开启事务
            $mgoodsModel->startTrans();
            $errcount = 0;

            ...
        
         if ($errcount == 0) {
                // 提交事务
                $mgoodsModel->commit();
                $this->outData['code'] = 1;
                $this->outData['msg']  = '添加成功';
                $this->printOut();


            } else {
                // 事务回滚
                $mgoodsModel->rollback();
                $this->outData['code'] = 2;
                $this->outData['msg']  = '添加失败';
                $this->printOut();
            }
        

小结。人生在于折腾,编程在于折腾,工作在于折腾。折腾过的东西,才属于你。

原文地址:https://www.cnblogs.com/jiqing9006/p/8066807.html