【问题标题】:How do I use friendsofcake/crud bulk delete?如何使用friendsofcake/crud批量删除?
【发布时间】:2019-07-24 01:52:22
【问题描述】:

文档在这里:https://crud.readthedocs.io/en/latest/actions/bulk-delete.html

但我不明白我的请求 URL 应该是什么样子才能批量删除?我认为这只是使用 DELETE 方法将模型作为 json 文件的常见粗略路径。但是,这似乎不起作用。

大概是因为我将它错误地映射到动作。以下是我作为控制器所做的工作:

namespace App\Controller\Api;

use Cake\Controller\Controller;

class ApiAppController extends Controller
{
    use \Crud\Controller\ControllerTrait;

    public $components = [
        'RequestHandler',
        'Crud.Crud' => [
            'actions' => [
                'Crud.Index',
                'Crud.View',
                'Crud.Add',
                'Crud.Edit',
                'Crud.Delete',
                'Crud.Bulk/Delete'
            ],
            'listeners' => [
                'Crud.Api',
                'Crud.ApiPagination',
                'Crud.ApiQueryLog',
                'Crud.Search'
            ]
        ]
    ]; 
}

我也试过这样的控制器:

use App\Controller\Api\ApiAppController;

/**
 * Devices Controller
 *
 * @property \App\Model\Table\DevicesTable $Devices
 *
 * @method \App\Model\Entity\Device[]|\Cake\Datasource\ResultSetInterface paginate($object = null, array $settings = [])
 */
class DataController extends ApiAppController
{
    public function initialize()
    {
        parent::initialize();
        $this->Crud->mapAction('deleteAll', 'Crud.Bulk/Delete');
    }
    public function deleteAll()
    {
        $connection = ConnectionManager::get('default');
        $results = $connection->execute('TRUNCATE TABLE data');
    }
}

在 URL 上进行各种尝试,如下所示:

DELETE http://my-site:8888/api/data.json
DELETE http://my-site:8888/api/data/delete.json
DELETE http://my-site:8888/api/data/delete-all.json
DELETE http://my-site:8888/api/data/all.json

当我收到 CSRF 令牌错误时,它似乎甚至没有命中 CRUD 插件。正常的 crud 路由不会出现 CSRF 错误,因为它们被路由拾取:

Router::prefix('api', function ($routes) {
        $routes->extensions(['json', 'xml']);
        $routes->resources('Data');
});

关于 RESTful 路由的 cakephp 文档没有介绍如何处理批量操作: https://book.cakephp.org/3.0/en/development/routing.html#resource-routes

【问题讨论】:

    标签: cakephp-3.0 crud


    【解决方案1】:

    所以我会考虑很多事情来解决这个问题。

    首先是您的路由。如果您使用的是DashedRoute,那么网址将是http://example.com/examples/delete-all.json。除非您还传递了 Accept: application/json 标头。

    您还可以在actions 配置中设置一个动作作为键,可用于更改动作名称。 See the documentation.

    'actions' => [
        'delete-all' => [
            'className' => 'Crud.Bulk/Delete'
        ]
    ]
    

    至于您的 CSRF 令牌问题,您需要解锁操作才能在不生成令牌的情况下使用 DELETE

    在您的控制器中 $this->Security->setConfig('unlockedActions', ['deleteAll']);

    或者您需要生成一个 CSRF 令牌并将其与您的请求一起发送。 Read more on CSRF in the book.

    【讨论】:

      猜你喜欢
      • 2010-10-18
      • 1970-01-01
      • 2018-09-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-05-25
      • 1970-01-01
      相关资源
      最近更新 更多