事务更新

此项目为例子

php的事务更新需要在logic层进行处理
修改src/Model/Logic/System/RolesLogic.php
以delete方法为例,在不使用事务处理的情况下:

1
2
3
4
5
6
7
8
9
    public function delete($id)
    {
        $entity1 = $this->rolesTable->get(5);
        $entity2 = $this->rolesTable->get($id);
        $result1 = $this->rolesTable->delete($entity1);
        $result2 = $this->rolesTable->delete($entity2);
        throw new Exception();
        return $result2;
    }

这个方法除了删除了本来的数据外还删除了id为5的数据,最后手动抛错

数据库更新前是这样的:

transactional-db

一共有5条数据。

使用postman访问api结果是:

with-out-transactional

api返回了错误,然后查看数据库的结果:

with-out-transactional

4和5两条记录都被删除了

然后将代码改成用事务处理:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
    public function delete($id)
    {
        // 定义事务要执行的内容
        $process = function() use($id){
            $entity1 = $this->rolesTable->get(5);
            $entity2 = $this->rolesTable->get($id);
            $result1 = $this->rolesTable->delete($entity1);
            $result2 = $this->rolesTable->delete($entity2);
            throw new Exception();
            return $result2;
        };

        $conn = $this->rolesTable->getConnection();  // 获取table的connection
        return $conn->transactional($process);  // 执行事务
    }

参照了官方文档中的cakephp3.9 transactional
可以直接使用connection中的transactional进行处理

再次使用postman访问api:

with-transactional

依然抛出了错误,但是查看数据库的内容:

with-transactional

数据并没有被删除,说明数据成功回滚了

将代码改成下面,进行正常的删除操作:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
    public function delete($id)
    {
        $process = function() use($id){
            $entity = $this->rolesTable->get($id);
            $result = $this->rolesTable->delete($entity);
            return $result;
        };

        $conn = $this->rolesTable->getConnection();
        return $conn->transactional($process);
    }

使用postman访问api:

with-transactional

返回了正常结果,查看数据库:

with-transactional

数据被正常删除了。