通过 Laravel API 为分组集合输出数据

问题描述 投票:0回答:2

我的问题是,我无法带来按类别分组的产品列表的输出,以便使用 Decodable 协议在 iOS 应用程序中进一步反序列化。

在我的 Laravel 10 应用程序中,有 3 个实体:购物车、产品和类别,它们之间建立了关系,一个类别可以包含许多产品,一个产品有一个类别,这部分有效。

当我收到购物篮中的必需产品时:

$collection = DB::table('cart_product')
    ->where('cart_id', $validRequest['cart_id'])
    ->join('products', 'cart_product.product_id', '=', 'products.id')
    ->join('categories', 'products.category_id', '=', 'categories.id')
    ->select('categories.name as category', 'cart_product.id', 'products.name as product', 'cart_product.count')
    ->get();

return $collection;

我得到以下输出:

[
  {
    "category": "Plumbing",
    "id": 2,
    "product": "Sink",
    "count": "1.00"
  },
  {
    "category": "Dairy products",
    "id": 1,
    "product": "Milk",
    "count": "2.00",
  },
  {
    "category": "Dairy products",
    "id": 5,
    "product": "Yogurt",
    "count": "4.00",
  }
]

将分组方法应用到groupBy集合之后

return $collection->groupBy('category');
,我得到了一个分组集合:

{
  "Plumbing": [
    {
      "category": "Plumbing",
      "id": 2,
      "product": "Sink",
      "count": "1.00"
    }
  ],
  "Dairy products": [
    {
      "category": "Dairy products",
      "id": 1,
      "product": "Milk",
      "count": "2.00",
    },
    {
      "category": "Dairy products",
      "id": 5,
      "product": "Yogurt",
      "count": "4.00",
    }
  ]
}

但是为了响应请求,我需要提供带有静态键的数据,这些数据将来应该在消费者应用程序中正确反序列化,即对应于以下示例:

[
  {
    "category": "Plumbing",
    "products": [
      {
        "id": 2,
        "product": "Sink",
        "count": "1.00"
      }
    ]
  },
  {
    "category": "Dairy products",
    "products": [
      {
        "id": 1,
        "product": "Milk",
        "count": "2.00",
      },
      {
        "id": 5,
        "product": "Yogurt",
        "count": "4.00",
      }
    ]
  }
]

我尝试了官方文档中有关使用集合的各种示例(group By、group

By()
+
map()
mapWithKeys()
mapToGroups()
),尝试在资源和集合处理程序中执行此处理,但我可以无法以正确的格式输出数据,Google 也没有对我的问题给出相关答案。

我请求帮助解决问题。

laravel collections response codable
2个回答
0
投票

试试这个可能对你有帮助

$collection = DB::table('cart_product')
    ->where('cart_id', $validRequest['cart_id'])
    ->join('products', 'cart_product.product_id', '=', 'products.id')
    ->join('categories', 'products.category_id', '=', 'categories.id')
    ->select('categories.name as category', 'cart_product.id', 'products.name as product', 'cart_product.count')
    ->get();

$collection = $collection->groupBy('category')->map(function ($item, $key) {
    return [
        'category' => $key,
        'products' => $item->map(function ($product) {
            return [
                'id' => $product->id,
                'product' => $product->product,
                'count' => $product->count
            ];
        })->values()
    ];
})->values();

          

0
投票

要解决此问题,请使用以下代码:

$cartData = Cart::with('products.category')->get();
    
    $result = [];
    
    foreach ($cartData as $cart) {
        $result[] = [
            'category' => $cart->products->first()->category->name,
            'products' => $cart->products->map(function ($product) {
                return [
                    'id' => $product->id,
                    'product' => $product->name,
                    'count' => $product->pivot->count,
                ];
            })->toArray(),
        ];
    }
    
    // Convert the result to JSON
    $jsonResult = json_encode($result, JSON_PRETTY_PRINT);
    
    // Output or return the JSON result
    echo $jsonResult;
© www.soinside.com 2019 - 2024. All rights reserved.