API Resource 中拼接额外数据

class IndexResource extends JsonResource {
    public function toArray($request) {
        // 将数组拼接到 ItemResource 中
        $all_category = [
            'id' => 0,
            'title' => '全部',
            'order' => "99999"
        ];

        return [
            'items' => ItemsResource::collection(Item::all())->concat(
                $all_category
            ),
        ];
    }
}

concat() 在结果最后一个,prepend() 在结果第一个。

悲观者永远正确,乐观者永远前行。
《L04 微信小程序从零到发布》
从小程序个人账户申请开始,带你一步步进行开发一个微信小程序,直到提交微信控制台上线发布。
《L03 构架 API 服务器》
你将学到如 RESTFul 设计风格、PostMan 的使用、OAuth 流程,JWT 概念及使用 和 API 开发相关的进阶知识。
讨论数量: 1
sanders

从楼主命名看,应该是针对接口定义的 ApiResource

借帖子问一下大家如何使用 ApiResource。我们目前大部分情况是根据模型创建 ApiResource,导致的问题是:

在模型查询约束了字段或预加载关系时,需要用做大量的判断,如:

class ShopResource extends JsonResource
{
    use GenPipeline;

    /**
     * @param \Illuminate\Http\Request $request
     * @return array|\Illuminate\Support\Collection
     */
    public function toArray($request)
    {

        return  $this->when($this->resource, function () use ($request) {

            return  $this->genPipeline(config('pipes.shop.shop_resource', []))
                ->send($this)
                ->then(function ($passable) {

                    return [
                        'id' => $this->id, // 必返回的字段
                        'name' => $this->name, // 必反回的字段
                        // 距离 根据字段可选返回
                        'distance' => $this->when(Arr::exists($this->getAttributes(), 'distance'), function() {
                            return number_format($this->distance, 2, '.', '');
                        }),
                        // 门店组合 根据模型关系可选返回
                        'combination' => $this->when($this->relationLoaded('combination'), function() {
                            return $this->combination ? ShopCombinationResource::make($this->combination) : [];
                        }),
                        // 门头图片 根据字段可选返回
                        $this->mergeWhen(Arr::exists($this->getAttributes(), 'doorway_image_key'), function() {
                            return [
                                'doorwayImageKey' => $this->doorway_image_key,
                                'doorwayImageUrl' => $this->doorway_image_key ? Storage::url($this->doorway_image_key) : '',
                            ];
                        }),
                    ];
                });
        });
    }
}

这样做的好处自然是可以在不同接口保持资源输出结构统一,但缺点就是这个类型的代码过于臃肿。

1年前 评论