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

报告相同问题?

悬赏问题

  • ¥100 连续两帧图像高速减法
  • ¥15 组策略中的计算机配置策略无法下发
  • ¥15 如何绘制动力学系统的相图
  • ¥15 对接wps接口实现获取元数据
  • ¥20 给自己本科IT专业毕业的妹m找个实习工作
  • ¥15 用友U8:向一个无法连接的网络尝试了一个套接字操作,如何解决?
  • ¥30 我的代码按理说完成了模型的搭建、训练、验证测试等工作(标签-网络|关键词-变化检测)
  • ¥50 mac mini外接显示器 画质字体模糊
  • ¥15 TLS1.2协议通信解密
  • ¥40 图书信息管理系统程序编写