Laravel API资源集合从其他资源返回特定字段

时间:2020-01-22 20:46:31

标签: laravel laravel-5 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"
            ]
        },
]

这是NewsResource 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),
        ];
    }

1 个答案:

答案 0 :(得分:0)

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

例如,您可以使用其他查询

/** 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),
];