duanliaouu965826 2019-03-20 07: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 08: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,
          ];
       }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?