首页 > 解决方案 > Laravel API 资源集合从其他资源返回特定字段

问题描述

我正在开发一个可通过移动应用程序访问的 api。

我已经为各个端点定义了资源和集合。我现在的问题是我想根据收集的内容返回不同的 api json 数据。

这是一个例子

省份有城市和郊区,所以json格式我需要有

    "data": [
        {
            "id": 1,
            "name": "Eastern Cape",
            "cities": [
                {
                    "name": "Alice"
                },
            ],
            "suburbs": [
                    "name": "Suburb 1"
            ]
        },
]

在新闻 api 集合中调用城市资源时,我想要不同的数据

    "data": [
        {
            "id": 1,
            "name": "Eastern Cape",
            "cities": [
                {
                    "name": "Alice",
                    "municipality": "municipality name",
                },
            ],
            "suburbs": [
                    "name": "Suburb 1",
                    "ward_number": "ward 1"
            ]
        },
]

这是一个新闻资源 API

    public function toArray($request)
    {
        // return parent::toArray($request);
        return [
            'id'=> $this->id,
            'title' => $this->title,
            'slug' => $this->slug,
            'content' => $this->content,
            'created_at' => $this->created_at,
            'category_id' => $this->news_category_id,
            'featured_image' => url($this->featured_image),
            'author' => new UserResource($this->user),
            'category' => new NewsCategoryResource($this->category), //Only category Name to be displayed
            'municipality' => new MunicipalityResource($this->municipality), // Only Municipality Name to be displayed
            'comments' => new NewsCommentResource($this->comments),
        ];
    }

标签: laravellaravel-5laravel-api

解决方案


我真的不知道你的代码结构是什么,但希望这对你有帮助

您可以使用不同的查询,例如

/** For the obvious resource calling */
return SomeResource::collection (SomeModel::with(['suburbs', 'cities'])
    /** Other filter queries */
    ->get());

/** For the cities resource calling */
return SomeResource::collection (SomeModel::with(['suburbs:id,ward_number', 'cities:id,municipality'])
    /** Other filter queries */
    ->get());

在用于城市/郊区数据的资源类中,这样做

return [
    /** Some data which you need */
    'municipality' => $this->when($this->municipality !== null, $this->municipality),
    'ward_number' => $this->when($this->ward_number !== null, $this->ward_number),
];

推荐阅读