【发布时间】:2020-05-09 02:25:06
【问题描述】:
我正在开发一个可通过移动应用访问的 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),
];
}
【问题讨论】:
-
那么 api route
api/foo/将返回您的第一个 json 并且api/bar将返回您的第二个 json 作为示例? -
是的,两者都使用不同的 api 端点
标签: laravel laravel-5 laravel-api