diff --git a/beike/Helpers.php b/beike/Helpers.php index abcf33b5..8f3aa32a 100644 --- a/beike/Helpers.php +++ b/beike/Helpers.php @@ -112,7 +112,7 @@ function locale(): string */ function currency_format($price): string { - return '$' . $price; + return '$' . number_format($price, 2); } /** diff --git a/beike/Models/Cart.php b/beike/Models/Cart.php index 6a6d818a..b937f060 100644 --- a/beike/Models/Cart.php +++ b/beike/Models/Cart.php @@ -13,6 +13,6 @@ class Cart extends Model public function sku() { - return $this->belongsTo(ProductSku::class); + return $this->belongsTo(ProductSku::class, 'product_sku_id', 'id'); } } diff --git a/beike/Shop/Http/Controllers/CartController.php b/beike/Shop/Http/Controllers/CartController.php index e6c1b092..412ce6e5 100644 --- a/beike/Shop/Http/Controllers/CartController.php +++ b/beike/Shop/Http/Controllers/CartController.php @@ -13,6 +13,7 @@ class CartController extends Controller $data = [ 'carts' => CartService::list(current_customer()) ]; + dump($data); return view("cart", $data); } diff --git a/beike/Shop/Http/Resources/CartList.php b/beike/Shop/Http/Resources/CartList.php new file mode 100644 index 00000000..14fb0546 --- /dev/null +++ b/beike/Shop/Http/Resources/CartList.php @@ -0,0 +1,33 @@ +sku; + $price = $sku->price; + $subTotal = $price * $this->quantity; + return [ + 'product_id' => $this->product_id, + 'sku_id' => $this->product_sku_id, + 'image' => image_resize($sku->image), + 'price' => $price, + 'price_format' => currency_format($price), + 'quantity' => $this->quantity, + 'subtotal' => $subTotal, + 'subtotal_format' => currency_format($subTotal), + ]; + } +} diff --git a/beike/Shop/Services/CartService.php b/beike/Shop/Services/CartService.php index 8e610a6f..3d051947 100644 --- a/beike/Shop/Services/CartService.php +++ b/beike/Shop/Services/CartService.php @@ -11,19 +11,18 @@ namespace Beike\Shop\Services; - use Beike\Models\Cart; -use Beike\Models\Customer; -use Beike\Models\ProductSku; +use Beike\Shop\Http\Resources\CartList; class CartService { - public static function list($customer) + public static function list($customer): array { if (empty($customer)) { return []; } - $cartList = Cart::query()->where('customer_id', $customer->id)->get(); + $cartItems = Cart::query()->where('customer_id', $customer->id)->get(); + $cartList = CartList::collection($cartItems)->jsonSerialize(); return $cartList; }