Php 我想在Laravel集合中返回一些键和值
我有两种型号(商店、产品),关系有很多Php 我想在Laravel集合中返回一些键和值,php,laravel,orm,relational-database,laravel-query-builder,Php,Laravel,Orm,Relational Database,Laravel Query Builder,我有两种型号(商店、产品),关系有很多 public function products(){ return $this->hasMany(Product::class); } 我想返回响应集合,在类StoresCollection扩展了ResourceCollection public function toArray($request) { return $this->collection->map(function ($item) {
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
}
}
为store_product创建一个资源,例如
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\u id
,因此我必须将Store\u id
添加到所选列的列表中 在您的情况下,可以通过get()
方法仅请求一些列,例如:
'store_product' => $item->products()->get(['id', 'is_featured']),
实现这一点非常简单
'store_product' => $item->products()->value('id', 'is_featured'),