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

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

最佳答案

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

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

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

关于Laravel API 资源集合从其他资源返回特定字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59867980/

相关文章:

php - 如何使用 laravel 或仅使用 native php 更新来自 mysql 数据库的 JSON 数据?

php - 如何在 laravel 的布局中将数据传递到我的标题?

php - 如何使用 laravel 在 MySQL 中通过将两个列值合并为一列来更新列

php - Laravel 在 Controller 中使用非 Laravel Composer 包

Laravel 的时间戳有奇怪的返回格式

mysql - SQLSTATE[23000] : Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails

html - 如何在 Laravel Blade 模板中添加输入类型 ="number"?

php - Laravel 5.4 Eloquent 查询

php - 如何将 Laravel 与 Nuxt js 集成