总结所有项目价格并将它们乘以它们在laravel中的透视表

问题描述:

我有一个问题需要在这里解决,我需要计算购物车的总价格。总结所有项目价格并将它们乘以它们在laravel中的透视表

我添加了多个产品到我的购物车。他们有价格和数量的关键。 事情是这样的:

{ 
"id": 1, 
"user_id": "1", 
"status": "closed", 
"total_price": "100", 
"created_at": "2017-07-22 06:06:17", 
"updated_at": "2017-07-22 08:02:04", 
"skues": [ 
    { 
     "id": 1, 
     "title": "مربعی ۵x2", 
     "description": "مربعی ۵x2، مربعی ۵x2 است.", 
     "sku_card_theme": "#2222", 
     "visible": "hidden", 
     "price": "50", 
     "category_id": "2", 
     "created_at": "2017-07-22 06:50:02", 
     "updated_at": "2017-07-22 07:16:33", 
     "pivot": { 
      "cart_id": "1", 
      "sku_id": "1", 
      "feature": "{\"size\": \"big\",\"quantity\": 2}", 
      "image_path": "images/users5e51d08006fed056b19db7d041d5688f.jpeg", 
      "id": 1 
     } 
    }, 
    { 
     "id": 1, 
     "title": "مربعی ۵x2", 
     "description": "مربعی ۵x2، مربعی ۵x2 است.", 
     "sku_card_theme": "#2222", 
     "visible": "hidden", 
     "price": "50", 
     "category_id": "2", 
     "created_at": "2017-07-22 06:50:02", 
     "updated_at": "2017-07-22 07:16:33", 
     "pivot": { 
      "cart_id": "1", 
      "sku_id": "1", 
      "feature": "{\"size\": \"big\",\"quantity\": 2}", 
      "image_path": "images/users/416e9f70dee50547866e9e89696d16e3.jpeg", 
      "id": 2 
     } 
    }, 
    { 
     "id": 3, 
     "title": "تقویم دیواری", 
     "description": "سشیشیش", 
     "sku_card_theme": "#2222", 
     "visible": "hidden", 
     "price": "25", 
     "category_id": "3", 
     "created_at": "2017-07-22 07:56:45", 
     "updated_at": "2017-07-22 07:56:45", 
     "pivot": { 
      "cart_id": "1", 
      "sku_id": "3", 
      "feature": "{\"size\": \"big\",\"quantity\": 2}", 
      "image_path": "images/users/273c1f5e3324815a82060931f30ead97.jpeg", 
      "id": 3 
     } 
    }, 

] 

我想在这里总结所有skues价格,并通过他们的支点数量乘以他们,我尝试了一些方法,如foreach,laravel收集each和其他办法...

但我没有答案。

我的代码示例:

$skues->each(function ($item) { 
    $quantity = json_decode($item->pivot->feature)->quantity; 
    $price = $item->price; 
}); 
$total_price = $quantity * $price; 

它有一个错误,告诉我,$quantity$price是不确定的变量。

,这是我的foreach方法:

foreach ($cart->skues as $skue) { 
    $quantity = json_decode($skue->pivot->feature)->quantity; 
    $total_price = $skue->price * $quantity; 
} 
$cart->update([ 
    'total_price' => $total_price, 
]); 

谢谢。

+0

你可以重复的var_dump($用品 - >支点),告诉我们你怎么看? –

我固定它最后:

public function total($cart) { 
     $cart->update([ 
          'total_price' => NULL, 
         ]); 
     $cart->skues->each(function ($item) { 
      $user  = auth()->user(); 
      $quantity = json_decode($item->pivot->feature)->quantity; 
      $price  = $item->price; 
      $total_price = $price * $quantity; 
      $user->cart->update([ 
            'total_price' => $total_price + $user->cart->total_price, 
           ]); 
     }); 
    } 
+0

可能不是最好的解决方案,但它的工作原理!请有人知道更好的答案 – Katerou22