【发布时间】:2019-12-30 02:08:47
【问题描述】:
我为我在 Laravel 的购物写了一个购物车,但总价计算错误。 我的 Cart.php 是:
<?php
namespace App;
class Cart {
public $items;
public $totalQty = 0;
public $totalPrice = 0;
public function __construct($oldCart)
{
if ($oldCart)
{
$this->items = $oldCart->items;
$this->totalQty = $oldCart->totalQty;
$this->totalPrice = $oldCart->totalPrice;
}
}
public function add($item , $id,$width,$height,$order,$count)
{
$storedItem = [
'id' =>$item->id,
'order' => $order,
'qty' => 0,
'width' => $width,
'height' => $height,
'priceperunit' => $item->priceperunit,
'price' => $item->price,
'item' => $item
];
if ($this->items)
{
if(array_key_exists($id, $this->items))
{
$storedItem = $this->items[$id];
}
}
if ($count)
{
$storedItem['qty'] += $count;
}
else
{
$storedItem['qty']++;
}
if ($storedItem['order'])
{
$storedItem['price'] = $storedItem['width'] * $storedItem['height'] * $storedItem['priceperunit'] * $storedItem['qty'];
$this->items[] = $storedItem;
}
else
{
$storedItem['price'] = $item->price * $storedItem['qty'];
$this->items[$id] = $storedItem;
}
if ($count)
{
$this->totalQty += $count;
}
else
{
$this->totalQty++;
}
$this->totalPrice += $storedItem['price'];
}
}
当我只添加一个项目时,总数和数量是可以的,但是当我添加第二个项目时,它会计算三倍,当我再次添加它时,它会计算四倍。
这是我的购物车物品:
{
"items": {
"172": {
"id": 172,
"qty": 2,
"price": 160,
"item": {
"id": 172,
"name": "R3-60",
"desc": null,
"price": "80",
}
}
}
}
和我的购物车总数:
{
"totalPrice": 240,
"totalQty": 2
}
【问题讨论】:
-
{ "items": { "172": { "id": 172, "qty": 3, "price": 240, "item": { "id": 172, "name": "R3-60", "desc": null, "price": "80", } } } }和总数是{ "totalPrice": 480, "totalQty": 3 }
标签: php laravel cart shopping-cart