繁体   English   中英

Laravel资源和相关表

[英]Laravel resource and related tables

我正在获取我的帖子资源和这篇文章我也收集他们的类别,但类别附带完整的数据,我需要限制返回的类别数据,

样品

<?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,
        ];
    }
}

上面的代码返回数据如:

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"

我需要的表单类别是TitleSlug

如何仅将类别数据限制为titleslug

试试下面的代码,我在你的代码中做了一些修改,

<?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,
      ];
   }
}

注意:添加您的CategoryResource取决于您的关系。

并为Category CategoryResource创建资源

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM