duanliaouu965826 2019-03-19 23:49
浏览 104
已采纳

Laravel资源和相关表

I am getting my posts with resources and with this posts I also collect their categories but the categories come with full data, I need to limit returned data of categories,

Sample

<?php

namespace App\Http\Resources;

use Illuminate\Http\Resources\Json\JsonResource;

class PostResource extends JsonResource
{
    public function toArray($request)
    {
        return [
            'id' => $this->id,
            'title' => $this->title,
            'url' => $this->slug,
            'body' => $this->body,
            'user' => $this->user,
            'categories' => $this->categories,
            'created_at' => (string) $this->created_at,
            'updated_at' => (string) $this->updated_at,
        ];
    }
}

Code above return data like:

0   
id  75
title   "Fpost title"
url "post-slug"
body    "post_body"
user    {…}
categories  
 0  
  id    1
  title "xx"
  slug  "xx"
  photo "xx"
  meta_tags "xx"
  meta_description  "xx"
  status    "xx"
  created_at    "xx"
  updated_at    "xx"
  pivot {…}
 1  
  id    9
  title "xx"
  slug  "xx"
  photo "xx"
  meta_tags "xx"
  meta_description  "xx"
  status    "xx"
  created_at    "xx"
  updated_at    "xx"
  pivot {…}
created_at  "xx"
updated_at  "xx"

Form categories all I need is Title & Slug.

Question

How do I limit categories data to title and slug only?

展开全部

  • 写回答

1条回答 默认 最新

  • douwen5066 2019-03-20 00:03
    关注

    Try the below code, I made some changes in your code,

    <?php
    
    namespace App\Http\Resources;
    
    use Illuminate\Http\Resources\Json\JsonResource;
    
    class PostResource extends JsonResource
    {
       public function toArray($request)
       {
          return [
            'id' => $this->id,
            'title' => $this->title,
            'url' => $this->slug,
            'body' => $this->body,
            'user' => $this->user,
            'categories' => CategoryResource::collection($this->whenLoaded('categories')),
            'created_at' => (string) $this->created_at,
            'updated_at' => (string) $this->updated_at,
          ];
       }
    }
    

    Note: add your CategoryResource depends on your relation.

    and create a resource for Category CategoryResource

    class CategoryResource extends JsonResource
    {     
      public function toArray($request)
       {
          return [
            'title' => $this->title,
            'url' => $this->slug,
          ];
       }
    }
    

    展开全部

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部