看板 PHP 關於我們 聯絡資訊
目前我建立了一個 resource 來轉換 model 的輸出資料格式,在 controller 中有兩個方法的返回值會使用到這個 resource,但是我想讓不同方法使用這個 resource 時,可以返回不同的資料,比如 index 方法只返回 id, st 程式碼大約如下(有稍微修改) Resource : class testResource extends Resource { public function toArray($request) { return [ 'id' => $this->id, 'name' => $this->name ]; } } Controller 中的方法: use testResource; public function index() { { { $test = Test::paginate(10); $this->response(testResource::collection($test); } public function store() { $test = Test::find(1): $this->response(new testResource($test)); } -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 39.12.160.253 ※ 文章網址: https://www.ptt.cc/bbs/PHP/M.1521908086.A.F18.html
DongFeng: paginate跟find的查詢結果就已經是不一樣的物件了,有03/25 00:22
DongFeng: 什麼一定要使用同一個method的理由嗎?03/25 00:22
※ 編輯: gonjay (39.8.36.111), 03/25/2018 08:09 您好,是因為目前我建立了兩個 resource 來分別定義返回的資料格式,但是想說如果 您好,是因為目前我建立了兩個 resource 來分別定義返回的資料格式,但是想說如果 之後建立更多方法的話,返回的資料格式又都不同的話,那就會建立好幾個 resource …,因此想說可不可以只使用一個 resource 就能返回不同的資料格式,謝謝~ ※ 編輯: gonjay (39.8.36.111), 03/25/2018 08:25:13 ※ 編輯: gonjay (39.8.36.111), 03/25/2018 08:26:12 ※ 編輯: gonjay (59.127.195.148), 03/25/2018 11:31:18
ChenCH1986: Transformer03/25 21:08
DongFeng: /README.md03/25 23:42
DongFeng: 我覺得上面這個套件應該可以達到你想要的效果03/25 23:43
DongFeng: 看一下 Alternate Transformations 這個章節03/25 23:43
謝謝樓上各位! ※ 編輯: gonjay (27.242.64.87), 03/27/2018 20:19:13