使用 Laravel 收集方法汇总多个购物车中的商品总数

Sum total items in multiple shopping carts using Laravel collection methods

假设我有一个购物车关系:

public function items()
{
  return $this->belongsToMany(Item::class, 'cart_item', 'cart_id', 'item_id')->withPivot('quantity');
}

假设我有多个 $carts,每个 $cart->items,我想生成一个包含此购物车中所有项目的列表,并在 pivot.quantity 上求和。

例如:

[
  {'item': Apple, 'pivot.quantity': 2},
  {'item': Orange, 'pivot.quantity': 1},
]

[
  {'item': Apple, 'pivot.quantity': 4},
  {'item': Banana, 'pivot.quantity': 1},
]

会产生

[
  {'item': Apple, 'pivot.quantity': 6},
  {'item': Banana, 'pivot.quantity': 1},
  {'item': Orange, 'pivot.quantity': 1},
]

我的想法是首先遍历所有 $carts 以生成如下列表:

[$cart[0]->items[0], $cart[0]->items[1], …, $cart[n]->items[n]]

是否可以在一行中实现这样的功能?

然后求和将是微不足道的 groupBy('item'),然后是适当的 sum

这应该有效

 $carts = [
   // this is your array;
 ];    

 $newCart = collect($carts)->flatten(1)->groupBy("item")->map(function($q){
    $item = $q->first()['item'];

    $quantity = $q->reduce(function($carry, $item){
        // Use this, as your quantity is not an object 
        // of pivot 
        return $carry + $item['pivot.quantity'];
        // use this if quantity is an object of pivot
        return $carry + $item['pivot']['quantity'];
    });

    return compact("item","quantity");
})->values();

希望对您有所帮助。