2015-06-16 35 views
1

我的問題類似於this one。我明白那裏給出的答案。這個問題的OP似乎沒有我的問題。從CakePHP REST API中移除資源包裝器JSON

我正在使用CakePHP 2.2.3。我取這樣的資源:

http://cakephpsite/lead_posts.json 

而且它返回結果是這樣的:

[ 
    { 
     "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

使用Hash utility改寫結果設置數據視圖之前返回: - 這樣的LeadPost指數被刪除

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')將改寫你的陣列。它不會保留原始數組索引,但除非你在afterFind回調中弄亂了它們應該是相同的。

您可以按照burzum的建議在模型的afterFind中執行此操作,但在Controller中執行此操作感覺更自然,因爲我們正在爲View準備數據。

+0

你會不會碰巧知道爲什麼記錄首先被包裹起來?這似乎是非標準的,我找不到有關這個事實的任何CakePHP文檔。 –

+0

@TylerCollier Cake的find方法總是(不包括'find('list')')別名索引來區分哪些模型數據屬於哪個。如果您使用可包含的行爲在相同的'find'中獲取關聯的模型,您將會看到每個表的數據都被別名正確索引。您可以做很多操作使用強大的Hash實用程序返回的結果來獲取更符合您需要的格式的數據。希望這能回答你的問題。不知道我解釋得很好。 – drmonkeyninja

+0

來自文檔的實際操作示例:http://book.cakephp.org/2.0/en/models/associations-linking-models-together.html#hasone – drmonkeyninja

0

你有兩個選擇:

  1. 使用一個afterFind()模型回調重新格式化標準數據結構體。但是,這也將重新格式化爲其他呼叫。
  2. Or use JSON views

除了移動視圖文件中的邏輯之外,兩者基本上相同。第二個選擇是更好的因此。

+0

我更喜歡drmonkeyninja的回答,因爲正如他所提到的,在控制器中似乎是正確的做法。我不喜歡在視圖中這樣做的想法,因爲我不想在每個視圖中都這樣做,所以在代碼中看起來就像是乾的方式。 –