2017-07-22 56 views
1

我有一個問題需要在這裏解決,我需要計算購物車的總價格。總結所有項目價格並將它們乘以它們在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($用品 - >支點),告訴我們你怎麼看? –

回答

1

我固定它最後:

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

相關問題