首页 > 解决方案 > 我想在 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
    }
}

标签: phplaravelormrelational-databaselaravel-query-builder

解决方案


在您的情况下,可以按get()方法仅请求某些列,例如:

'store_product' =>  $item->products()->get(['id', 'is_featured']),

推荐阅读