laravel - 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),
];
}
解决方案
我真的不知道你的代码结构是什么,但希望这对你有帮助
您可以使用不同的查询,例如
/** 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),
];
推荐阅读
- javascript - 对象键的数字顺序从 0 javascript 重新排列
- c - 当它是 sizeof() 函数的参数时,为什么 n++ 不起作用?
- celery - 我可以对 celery 任务对象进行本地回调吗?
- ios - 使用 iOS 将 Intel Realsense D435 连接到 iPhone
- c++ - 使用 std::thread 在 C++ 中的单独线程中执行每个对象
- tabs - Flutter - 如何正确删除 TabBarView 中的选项卡
- javascript - 需要一个 json 文件导致错误:找不到模块
- php - 如何在 http 标头上修改 joomla 网站中的 CSP
- arrays - 角度 forEach 中的数组表示法
- css - Shadow DOM 样式封装