修改

需求:修改角色的时候增加角色的权限或新增权限

1.Controller:

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

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
<?php
// 会接受PUT以及PATCH的请求,并且会带上ID
public function edit($id)
{
    $data = json_decode($this->request->getBody(), true);
    $result = RolesLogic::instance()->save($id, $data);
    if ($result == null) {
        $this->responseError("record not found!");
        return;
    }
    $this->responseOk($result);
}

2.Logic:

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

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
<?php
use Cake\Datasource\Exception\RecordNotFoundException;

······
/**
 * 修改角色
 */
public function save($id, $data)
{
    try {
        $entity = $this->rolesTable->get($id);
    } catch (RecordNotFoundException $e) {
        return null;
    }
    $newData =  $this->camelToUnderscore($data);
    $entity = $this->rolesTable->patchEntity($entity, $newData, ["associated" =>"Permissions"]);
    $rolesTable = $this->rolesTable;
    $rolePermissionsTable = $this->rolePermissionsTable;
    $this->rolesTable->getConnection()->transactional(function () use ($rolesTable,$rolePermissionsTable, $entity, $id) {
        $rolePermissionsTable->deleteAll(['role_id =' => $id]);
        $result = $rolesTable->save($entity, ['atomic' => false]);
        return  $this->underscoreToCamel((array)$result);
    });
    return null;
}

2.1 get()方法

Cake\ORM\Table::get($primaryKey, options = []) 使用此函数可以获取主键为primaryKey的数据及其关联的数据,使用方式如下例:

1
2
<?php
$rolesTable->get(1, ['contain' => ['Permissions']]);

若不提供options,将会返回主键为primaryKey的数据。
当主键为$primaryKey的数据在数据库中不存在时,会抛出Cake\Datasource\Exception\RecordNotFoundException的异常,需要捕获异常,进行处理,例如:

1
2
3
4
5
6
<?php
try {
    $entity = $this->rolesTable->get($id);
} catch (RecordNotFoundException $e) {
    return null;
}

2.2 事务

$param为事务内需要的table,需要保存的数据以及其他参数,写法参照示例代码:

1
2
3
4
<?php
$xxxTable->getConnection()->transactional(function () use ($param1, $param2,···) {
    // 保存,删除等代码
});

2.3 updateAll()

CakeORM\Table::updateAll($fields, $conditions)

$fields:需要更新的字段数组,例如:['name' => 'neko']

$conditions:修改条件,例如:

1
2
3
<?php
// 将会把id>10的user的name字段更新为neko
$this->usersTable->updateAll(['name' => 'neko'],["id >" => 10]);

3.结果

使用postman访问 http://localhost:8000/system/roles 查看结果:
PUT 请求
php db
PATCH 请求
php db