php - 我想在 Laravel 集合中返回一些键和值
问题描述
我有两个模型(商店、产品)和关系 hasMany
public function products(){
return $this->hasMany(Product::class);
}
我想返回响应集合,在类 StoresCollection 扩展 ResourceCollection
public function toArray($request)
{
return $this->collection->map(function ($item) {
return [
'id' => $item->id,
'seller_id' => $item->seller_id,
'store_product' => $item->products()->get(),
];
});
}
但是我不想返回“store_product”中的每个键,我只需要“id”和“is_featured”,我不想要它们。
{
"status": "success",
"message": [],
"code": 200,
"data": [
{
"id": 5,
"seller_id": 6,
"store_product": [
{
"id": 1017,
"seller_id": 89,
"is_featured": 0,
"is_category_featured": 0,
"is_approved": 1,
"created_at": "2020-4-21T00:00:00.000000Z",
"updated_at": "2020-4-21T00:00:00.000000Z"
}
]
},
{
"id": 5,
"seller_id": 6,
"store_product": [
{
"id": 1018,
"seller_id": 89,
"is_featured": 0,
"is_category_featured": 0,
"is_approved": 1,
"created_at": "2020-4-21T00:00:00.000000Z",
"updated_at": "2020-4-21T00:00:00.000000Z"
}
]
},
"paging": {
"total": 2,
"per_page": 15,
"current_page": 1,
"last_page": 1,
"from": 1,
"to": 2
}
}
解决方案
在您的情况下,可以按get()
方法仅请求某些列,例如:
'store_product' => $item->products()->get(['id', 'is_featured']),
推荐阅读
- python - 导出由子流程解决和选择的路径的方法
- r - 在 R 工作室中,我收到一个带有交互的双向 ANOVA 的事后测试 TukeyHSD 错误
- python - 在 Amazon Linux 实例上运行 python 脚本时出现库错误
- mysql - 使用存储过程从不同的临时表更新主表 - MySQL
- html - 您如何使用 html 和 css 进行有条件的垂直换行
- python - 如何压缩python for循环
- c++ - Coverity 抱怨 htonl 操作数,但为什么呢?
- linux - 在我的 Mac 上删除 Anaconda 时遇到问题
- javascript - 使用缩放在 p5.js 中翻转图像
- github - 为什么我的 gh-pages 的 unfurl 'og:image' 没有出现在任何平台上?