【问题标题】:Decrease product quantity in database after order is placed with Laravel使用 Laravel 下订单后减少数据库中的产品数量
【发布时间】:2017-01-28 07:57:38
【问题描述】:

我在网站上有购物车,到目前为止一切正常。现在我正在尝试为管理员可以添加到后端的每种产品(已经完成)以及当客户订购产品以减少数据库中的数量时进行数量。

据我所说,管理面板已准备就绪,可以向保存在数据库中的产品添加数量。这是我的购物车提交控制器

public function orderSubmit() {
    $cart = Session::get(self::CART_SESSION_KEY, array());
    if (count($cart) < 1) {
        return Redirect::to('/');
    }

    $validatorRules = array(
        'captcha' => 'required|captcha'      
    );

    Input::merge(array_map('trim', Input::all()));
    $validator = Validator::make(Input::all(), $validatorRules);

    if ($validator->fails()) {
        return Redirect::to('/cart/order?_token=' . csrf_token())->withErrors($validator->errors())->withInput(Input::except(['captcha']));
    }

    $order = new Order();
    $order->user_id = self::$user->user_id;
    $order->data = json_encode($cart, true);
    $order->info = Input::get('additional_info');

    $order->save();
    Session::put(self::CART_SESSION_KEY, array());

    return Redirect::to('/)->with('message_success', 'Order created! We will contact you shortly to confirm your order details.');
}

购物车保存在$order-&gt;data = json_encode($cart, true); 中,并在产品等数据库信息中查找

{"title":"Test Product","description":"You save 25%","quantity":1,"price":135}

如果有多个产品在上面的数组中排列也会有。

我不明白的是如何提取订购了哪些产品以及从中提取了多少件,以便我以后可以更新每个产品的数据库数量字段?

我什至不知道从哪里开始。

【问题讨论】:

    标签: php mysql laravel-4 cart


    【解决方案1】:

    我做到了,并且工作得很好。

    $check_stock = Product::where('id', $product->product_id)->first()->stock_quantity;
    
          if ($check_stock > 0 && $check_stock >= $product->quantity) {
            $stock = Product::where('id', $product->product_id)->decrement('stock_quantity', $product->quantity);
          }else{
            watchOut('warning', 'Opps', 'Stock shortage');
            return back();
          }
    

    【讨论】:

      【解决方案2】:

      对于那些使用资源控制器更简单/容易答案的人:

      public function create()
      {
          $stocks = Stock::all();
          //dd($stocks);
          return view('sales.create', compact('stocks'));
          //$sales = Sale::pluck('stock_id')->prepend('stock_id');
          //$sales = DB::table('stocks')->select('stock_id')->get();
          //return view('sales.create')->with('sales',$sales);
      }
      
      
      public function store(Request $request)
      {
          $this->validate($request, [
              'stock_id' => 'required',
              'product_name' => 'required',
              'sale_quantity' => 'required',
              'unit_selling_price' => 'required',
              'total_sales_cost' => 'required'
              ]);
      
          //create stock
          $sale = new Sale;
          $sale->stock_id = $request->input('stock_id');
          $sale->product_name = $request->input('product_name');
          $sale->sale_quantity = $request->input('sale_quantity');
          $sale->unit_selling_price = $request->input('unit_selling_price');
          $sale->total_sales_cost = $request->input('total_sales_cost');
          $sale->stock_quantity =
              $sale->save();
          DB::table('stocks')->where('stock_name', $request->input('product_name'))->decrement('stock_quantity', $request->input('sale_quantity'));
      
          return redirect('/sales')->with('success', 'Sale Saved');
      }
      

      【讨论】:

        【解决方案3】:

        假设 $cart 是一个数组,并且根据您提供的 json,您需要:

        1. 将产品 ID 添加到 $cart 否则几乎不可能知道该订单的产品是什么
        2. 使用 $cart 上每个产品的产品 ID,您现在可以循环购物车产品并更新它们。类似于以下代码。

          public function orderSubmit() {
              $cart = Session::get(self::CART_SESSION_KEY, array());
              if (count($cart) < 1) {
                  return Redirect::to('/');
              }
          
              $validatorRules = array(
                  'captcha' => 'required|captcha'      
              );
          
              Input::merge(array_map('trim', Input::all()));
              $validator = Validator::make(Input::all(), $validatorRules);
          
              if ($validator->fails()) {
                  return Redirect::to('/cart/order?_token=' . csrf_token())->withErrors($validator->errors())->withInput(Input::except(['captcha']));
              }
              \DB::beginTransaction();
          
              try {
                  $order = new Order();
                  $order->user_id = self::$user->user_id;
                  $order->data = json_encode($cart, true);
                  $order->info = Input::get('additional_info');
          
                  $order->save();
          
                  foreach ($cart as $item) {
                      $product = Product::find($item->id);
                      $product->decrement('votes', $item->quantity);
                  }
          
                  Session::put(self::CART_SESSION_KEY, array());
          
                  \DB::commit();
          
                  return Redirect::to('/')->with('message_success', 'Order created! We will contact you shortly to confirm your order details.');
              } catch (\Exception $ex) {
                  \DB::rollback();
          
                  return Redirect::to('/cart/order?_token=' . csrf_token())->withErrors($ex->getMessage())->withInput(Input::except(['captcha']));
              }
          }
          

        我添加了交易代码,以确保在正确存储订单时减少数量。

        【讨论】:

        • 抱歉我的回复晚了。我有点远。感谢您的回答。只有一个问题:我是否需要在问题的上述函数中添加此代码?
        • @Garg,我已经更新了答案并添加了完整的代码。您可以发现答案和问题代码之间的差异。
        猜你喜欢
        • 1970-01-01
        • 2020-09-05
        • 2016-08-16
        • 2017-11-13
        • 2014-05-04
        • 1970-01-01
        • 2019-04-21
        • 2020-12-16
        • 2021-09-03
        相关资源
        最近更新 更多