我想返回Laravel收藏中的一些密钥和值



我有两个模型(商店、产品(,关系有很多

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"one_answers"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']),

为store_product创建一个Resource,例如StoreProductResource,并在toArray((方法中定义键。

然后返回并修改StoreCollection::toArray((,如下所示:

return $this->collection->map(function ($item) {
return [
'id' => $item->id,
'seller_id' => $item->seller_id,
'store_product' =>  StoreProductResource::collection($item->products()->get()),
];
});

我还认为回调映射在您的用例中是不必要的。toArray((只需要返回一个数组。Laravel处理映射。除了你在回调中做的一些逻辑没有包含在同一代码中。

您也可以定义要在关系中返回的密钥:

public function products(){
return $this->hasMany(Product::class)->select(['store_id','id', 'is_featured']);
}

注意:记住添加分配给匹配两个表的外键的列。例如,在我的示例中,我假设Store具有Product,这意味着分配给外键的列将类似于store.id = product.store_id,所以我必须将store_id添加到所选列的列表中;

实现这个非常简单

'store_product' =>  $item->products()->value('id', 'is_featured'),

最新更新