从 CakePHP REST 中删除资源包装器 API JSON

Remove resource wrapper from CakePHP REST API JSON

我的问题类似于this one。我理解那里给出的答案。该问题的OP似乎没有我的问题。

我正在使用 CakePHP 2.2.3。我正在获取这样的资源:

http://cakephpsite/lead_posts.json

它 returns 结果是这样的:

[
    {
        "LeadPost": {
            "id": "1",
            "fieldA": "blah",
            "fieldB": "blah2",
        }
    {
        "LeadPost": {
            "id": "1",
            "fieldA": "blah",
            "fieldB": "blah2"
        }
    }
]

看到每个对象上的 LeadPost 包装器了吗?我不确定它为什么在那里。我想删除它。

LeadPost 模型扩展了 AppModel,否则为空。

LeadPostsController.php

class LeadPostsController extends AppController {

    public $components = array('RequestHandler');

    public function index() {
        $records = $this->LeadPost->find('all', ['limit' => 20]);
        $this->set(array(
            'leadposts' => $records,
            '_serialize' => 'leadposts'
        ));
    }
}

我的路由很简单:

Router::mapResources('lead_posts');
Router::parseExtensions();

您有两个选择:

  1. 使用 afterFind() 模型回调重新格式化标准数据结构。但这也将为其他调用重新格式化。
  2. Or use JSON views.

除了你在视图文件中移动了逻辑之外,两个与一个基本相同。因此,第二个选项更好。

使用Hash utility重写View设置数据前返回的结果:-

class LeadPostsController extends AppController {

    public $components = array('RequestHandler');

    public function index() {
        $records = $this->LeadPost->find('all', ['limit' => 20]);
        $this->set(array(
            'leadposts' => Hash::extract($records, '{n}.LeadPost'),
            '_serialize' => 'leadposts'
        ));
    }
}

此处 Hash::extract($records, '{n}.LeadPost') 将重写您的数组,以便删除 LeadPost 索引。它不会保留原始数组索引,但除非你在 afterFind 回调中弄乱了它们,否则它们应该是相同的。

您可以按照 burzum 的建议在模型的 afterFind 中执行此操作,但我觉得在控制器中执行此操作更自然,因为我们专门为视图准备数据。