删除

需求:删除角色的时候删除中间表的关联数据

1.Controller:

修改src\Controller目录下的RolesController.php,添加代码:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
<?php
// 接受DELETE请求
public function delete($id)
{
    if ($id <= 0) {
        $this->responseError();
    }
    $result = RolesLogic::instance()->delete($id);
    $this->responseOk($result);
}

2.Logic:

修改src\Model\Logic目录下的RolesLogic.php,添加代码:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
<?php
/**
 * 根据id删除
 */
public function delete($id)
{
    try {
        $entity = $this->rolesTable->get($id);
    } catch (RecordNotFoundException $e) {
        return null;
    }
    $result = $this->rolesTable->delete($entity);
    return $result;
}

2.1 delete()

CakeORM\Table::delete(EntityInterface $entity, $options = [])

  • $entity:需要删除的实体类

  • $options:可选项

    • atomic:是否在数据库事务中执行删除(默认值:true),使用delete函数时会默认启用事务进行删除,当需要手动开启事务时,可将此项设置为false。

    • checkRules:是否在删除前检查实体的删除规则,如果检查规则失败,将中止删除操作。(默认值:true)

2.1 deleteAll()

CakeORM\Table::deleteAll($conditions)

$conditions:删除条件,例如:

1
2
3
<?php
// 将会删除所有id>10的user
$this->usersTable->deleteAll(["id >" => 10]);

3.结果

使用postman访问 http://localhost:8000/system/roles/$id 查看结果: php db