簡體   English   中英

Laravel API 資源集合從其他資源返回特定字段

[英]Laravel API Resource Collection return specific fields from other resource

我正在開發一個可以通過移動應用程序訪問的 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),
        ];
    }

我真的不知道你的代碼結構是什么,但希望這對你有幫助

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

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

在用於城市/郊區數據的 Resource 類中,這樣做

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM