【问题标题】:How to add value to array without oerwritting and access those values如何在不写入和访问这些值的情况下向数组添加值
【发布时间】:2021-12-24 18:27:54
【问题描述】:

您好,我正在尝试将产品添加到购物车,但不会覆盖之前添加到购物车的产品,并且如果两个产品相同,则不会重复,而是将数量增加 1。

以下是我设置购物车并向其中添加产品的方式:

public function addToCart(Request $request)
    {
        $id = $request->product_id;
        $product = Product::find($id);
        $request->session()->put('cart', [
            [
                "id" => $product->id,
                "name" => $product->name,
                "price" => $product->price,
                "image" => $product->image,
                "quantity" => 1,],
        ]);
        $cart = $request->session()->only(['cart']);
        dd($cart);
        return redirect('cart');
    }

这就是我从dd得到的

array:1 [▼
  "cart" => array:1 [▼
    0 => array:5 [▼
      "id" => 1
      "name" => "name"
      "price" => 42.42
      "image" => "../image.jpg"
      "quantity" => 1
    ]
  ]
]

我尝试使用putcart[] = [product infos...] 而不是push,但它仍然会覆盖以前的产品

此外,我对如何单独访问存储在我的购物车中的每个产品感到困惑,我可以通过 $request->session()->only(['cart']) 访问整个购物车,但我找不到如何访问该购物车中的产品。

【问题讨论】:

    标签: laravel session cart


    【解决方案1】:

    问题出在这里:

     $request->session()->put('cart', [
                [
                    "id" => $product->id,
                    "name" => $product->name,
                    "price" => $product->price,
                    "image" => $product->image,
                    "quantity" => 1,],
            ]);
    

    您创建了两个数组。所以要么将此部分更改为:

     $request->session()->put('cart', [
                "id" => $product->id,
                "name" => $product->name,
                "price" => $product->price,
                "image" => $product->image,
                "quantity" => 1,
            ]);
    

    或这部分:

    cart[] = [product infos...]
    

    cart[0][] = [product infos...]
    

    但不是两者兼而有之。

    另外,一个更好和更常用的做法不是将整个购物车存储在会话中,而是将其存储在表 cartscart_items 中并仅存储在会话中一个哈希。

    【讨论】:

    • 哦,我明白了,谢谢!我将尝试创建新表来存储我的购物车。但是我不确定我的订单表应该是什么样子。
    • 好吧,通常你的购物车有 cart_items (cart_id),订单有 order_items (order_id),然后你有 cart_items 和 order_items 之间的 M:N 关系,例如 cart_item_order_item 表,其中包含数量等数据, 价格
    • 好的,感谢所有建议和帮助。
    猜你喜欢
    • 2018-02-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-06
    • 1970-01-01
    • 2019-06-25
    • 1970-01-01
    • 2018-08-29
    • 2019-12-25
    相关资源
    最近更新 更多