【问题标题】:Return different data for 2 different routes from the same model using API resource使用 API 资源从同一模型返回 2 条不同路线的不同数据
【发布时间】:2021-01-08 17:30:11
【问题描述】:

我有 2 条路线在控制器中命中 show()index() 方法。模型名称为 Feed,有 4 个关系 FeedType、FeedImage、FeedVideo 和 FeedCaption

当 API 命中 show() 方法时,我将通过 Feed 资源返回除 'thumbnail' 字段之外的所有字段和特定关系字段

class Feed extends JsonResource
{
    /**
     * Transform the resource into an array.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return array
     */
    public function toArray($request)
    {
        return [
            'id' => $this->id,
            'title' => $this->title,
            'content' => $this->content,
            'keywords' => $this->keywords,
            'slug' => $this->slug,
            'type' => new FeedTypeResource($this->feedType),
            'images' => FeedImageResource::collection($this->feedImages),
            'video' =>  new FeedVideoLinkResource($this->feedVideoLink),
            'caption' => new FeedCaptionResource($this->feedCaption),
        ];
    }
}

现在我只想返回 3 个字段 'title'、'thumbnail'、'created_at',其中一个关系字段 'name' 来自 FeedType当 API 命中 show() 方法时,通过资源的 strong> 关系。所以我创建了一个 FeedCollection 资源。但它给出了错误。

class FeedCollection extends ResourceCollection
{
    /**
     * Transform the resource collection into an array.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return array
     */
    public function toArray($request)
    {
        return [
            'title' => $this->title,
            'thumbnail' => $this->thumbnail,
        ];
    }
}

【问题讨论】:

  • 什么错误,这是需要了解的重要信息......而且您可能正在处理单个实体而不是集合

标签: laravel


【解决方案1】:

您可以使用chunk方法进行收集。 chunk 方法将集合分成多个给定大小的更小的集合:

$collection = collect([1, 2, 3, 4, 5, 6, 7]);

$chunks = $collection->chunk(4);

$chunks->all();

// [[1, 2, 3, 4], [5, 6, 7]]

在使用网格系统(如 Bootstrap)时,此方法在视图中特别有用。例如,假设您有一组 Eloquent 模型要在网格中显示:

@foreach ($products->chunk(3) as $chunk)
    <div class="row">
        @foreach ($chunk as $product)
            <div class="col-xs-4">{{ $product->name }}</div>
        @endforeach
    </div>
@endforeach

请参阅链接中的示例: https://laravel.com/docs/8.x/collections#method-chunk

【讨论】:

    猜你喜欢
    • 2012-05-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-07
    • 1970-01-01
    相关资源
    最近更新 更多