推车条件不会保存到laravel中的桌子上

时间:2018-02-18 06:11:51

标签: php laravel

我的购物车中有条件和无条件的商品,当我将购物车数据添加到orders表时,除了我的商品条件外,我的所有购物车数据都会保存。

my cart数据的日期:

CartCollection {#699 ▼
  #items: array:1 [▼
    2 => ItemCollection {#670 ▼
      #config: array:6 [▶]
      #items: array:6 [▼
        "id" => 2
        "name" => "product two"
        "price" => 50000.0
        "quantity" => 2
        "attributes" => ItemAttributeCollection {#671 ▼
          #items: array:1 [▼
            "attr" => array:2 [▼
              "name" => "weight"
              "value" => "2"
            ]
          ]
        }
        "conditions" => array:1 [▼
          0 => CartCondition {#672 ▼
            -args: array:4 [▼
              "name" => "12 inch"
              "value" => "25000"
              "type" => "additional"
              "target" => "item"
            ]
            -parsedRawValue: 25000.0
          }
        ]
      ]
    }
  ]
}
当我尝试保存在same cart表中时,

orders

Order {#680 ▼
  #fillable: array:16 [▶]
  #events: array:1 [▶]
  #casts: array:1 [▶]
  #connection: "mysql"
  #table: null
  #primaryKey: "id"
  #keyType: "int"
  +incrementing: true
  #with: []
  #withCount: []
  #perPage: 15
  +exists: true
  +wasRecentlyCreated: true
  #attributes: array:15 [▶]
  #original: array:15 [▼
    "product_data" => "{"2":{"id":2,"name":"product two","price":50000,"quantity":2,"attributes":{"attr":{"name":"weight","value":"2"}},"conditions":[{}]}}"
    "user_id" => 1
    "ordernu" => 9358964473
    "address_id" => "1"
    "orderstatus_id" => 1
    "quantity" => 2
    "payment_id" => null
    "buyer_name" => "John Doe"
    "note" => null
    "buyer_email" => "admin@admin.com"
    "phone" => "006281200000000"
    "price" => null
    "updated_at" => "2018-02-18 13:03:41"
    "created_at" => "2018-02-18 13:03:41"
    "id" => 10
  ]

如您所见,我的条件"conditions":[{}]}为空。

这是我的保存功能:

 //save cart to orders table and remove items from it
    public function checkout(Request $request)
    {
      $cartItems = Cart::getContent();

      try {
        $order = new Order();
        $status  = Orderstatus::where('title', 'Witing Payment')->value('id');
        $qty = Cart::getTotalQuantity();
        $order->product_data = $cartItems; //save cart data as json
        $order->user_id = Auth::user()->id;
        $order->ordernu = mt_rand(1000000000, 9999999999);
        $order->address_id = $request->input('address_id');
        $order->orderstatus_id = $status;
        $order->quantity = $qty;
        $order->payment_id = $request->input('payment_id');
        $order->buyer_name = $request->input('buyer_name');
        $order->note = $request->input('note');
        $order->buyer_email = $request->input('buyer_email');
        $order->phone = $request->input('phone');
        $order->price = $request->input('totalPriceInTotal');
        dd(Auth::user()->orders()->save($order)); // dd results
        Auth::user()->orders()->save($order);

        foreach ($cartItems as $item) {
            $product = Product::find($item->id);
            $product->decrement('stock', $item->quantity);
        }

      $user = $order->buyer_email;
      event(new UserOrdered($order));

      //Cart::clear(); //clear cart info
      Session::flash('success', 'Thank you. Your order has been received.');
      return redirect()->route('ordersindex');
      }catch (Exception $e) {
         return response($e->getMessage(), 400);
      }
    }

任何想法?

更新

这是我在购物车会话中添加产品的方式:

public function addingItem(Request $request, $id)
    {
      //finding product
      $product = Product::findOrFail($id);
      //get product weight
      $weight = $product->weight;
      //list of discounts
      $discounts = Discount::all();
      //get current time
      $mytime = Carbon::now();

      // get product weight in cart
      $weightArray = [
        'attr' => [
              'name' => 'weight',
              'value' => $weight,
        ]
      ];

      // add product conditions to cart
      $customAttributes = [];
      if(!empty($request->attr)){
          foreach($request->attr as $sub) {
          // find the suboption
              $sub = Suboption::find($sub);
              if (!empty($sub->id)) {
                  $itemCondition1 = new \Darryldecode\Cart\CartCondition(
                    [
                      'name' => $sub->title,
                      'value' => $sub->price,
                      'type' => 'additional',
                      'target' => 'item',
                    ]
                  );
                  array_push($customAttributes, $itemCondition1);
              }
          }
      }

      //adding product and options to cart
      Cart::add(array(
        'id' => $product->id,
        'name' => $product->title,
        'price' => $request->input('harga'),
        'quantity' => $request->input('quantity'),
        'attributes' => $weightArray,
        'conditions' => $customAttributes,
      ));
      //success message in return
      Session::flash('success', 'This product added to your cart successfully.');
      return redirect()->back();
    }

更新2

我一直在玩代码,我来到这段代码:

public function checkout(Request $request)
    {
      $cartItems = Cart::getContent();
      foreach($cartItems as $item){
          if (is_array($item['conditions'])) {
            foreach($item['conditions'] as $condition){
              $arsd = [
                'name' => $condition->getName(),
                'value' => $condition->getValue(),
              ];
             return $arsd;
            }
        }
      }

返回这个:(我需要的)

screen2

    "product_data" => "{

"16":{"id":16,"name":"new product","price":100000,"quantity":"1","attributes":{"attr":{"name":"weight","value":"56"}},"conditions":[{"args":null},{"args":null}]},

"4":{"id":4,"name":"product four","price":1500000,"quantity":"1","attributes":{"attr":{"name":"weight","value":"45"}},"conditions":[{"args":null}]},

"1":{"id":1,"name":"product one","price":10000000,"quantity":"1","attributes":{"attr":{"name":"weight","value":"1"}},"conditions":[]}
} ◀"

现在问题是如何在我的conditions部分代码中应用此功能?当我在保存到数据库(orders表)时我的购物车这是我得到的:

screen3

  

注意:ID为16&的产品4应该有条件和身份1   没有任何条件。

现在,有人可以提供帮助吗?

更新3

再次,我玩代码更多,现在我的订单表中有条件(有1个问题)

foreach($cartItems as $item)
      {
          $item->id; // the Id of the item
          $item->name; // the name
          if(is_array($item['conditions']) && !empty($item['conditions'])) {
            foreach($item['conditions'] as $key => $value)
            {
              $item['conditions'] = [
                    'name' => $value->getName(),
                    'value' => $value->getValue(),
                ];
            }
          }
          $item->price;
          $item->quantity; // the quantity
          $item->attributes; // the attributes
      }

结果:

"product_data" => "{"4":{"id":4,"name":"product four","price":1500000,"quantity":"1","attributes":{"attr":{"name":"weight","value":"45"}},"conditions":{"name":"12 inch","value":"25000"}}} ◀"
  

问题是我的表中只有1个条件,而我的项目有2个   条件。

有什么想法吗?

2 个答案:

答案 0 :(得分:1)

您可以在结帐功能上试试这个。

public function checkout(Request $request)
{
    $cartItems = Cart::getContent();
    foreach($cartItems as $item){
        if (is_array($item['conditions']) && !empty($item['conditions']) {
            foreach($item['conditions'] as $condition){
                $arsd = [
                    'name' => $condition->getName(),
                    'value' => $condition->getValue(),
                ];
                array_push($item['conditions']['args'], $arsd);
            }
        }
    }
    return $cartItems;
}

更新:

  

问题是我的表中只有1个条件而我的项目有2个条件。

当您的商品最初有2 condition时,您只能获得1 conditions,因为之前的价值被其他condition覆盖而不是添加它在循环期间到堆栈。在迭代$temp时保存item conditions变量的条件可能会解决这个问题。请参阅以下更新代码:

foreach ($cartItems as $item) {
    $item->id; // the Id of the item
    $item->name; // the name
    if (is_array($item['conditions']) && !empty($item['conditions'])) {
        $temp = [];
        // get the subtotal with conditions applied
        $item['price_sum'] = $item->getPriceSumWithConditions();

        foreach ($item['conditions'] as $key => $value) {
            $temp[] = [
                'name' => $value->getName(),
                'value' => $value->getValue(),
            ];
        }

        $item['_conditions'] = $temp;
    }
    $item->price;
    $item->quantity; // the quantity
    $item->attributes; // the attributes
}

答案 1 :(得分:1)

可能是您可以尝试以下

foreach($cartItems as $item)
      {
          $item->id; // the Id of the item
          $item->name; // the name
          if(is_array($item['conditions']) && !empty($item['conditions'])) {
            $conditions=[];
            foreach($item['conditions'] as $key => $value)
            {
                $conditions[]=[
                    'name' => $value->getName(),
                    'value' => $value->getValue(),
                ];

            }
            if(count($conditions)){
                $item->price=$item->getPriceSumWithConditions();
            }
            $item['conditions'] = $conditions;
          }
          $item->price;
          $item->quantity; // the quantity
          $item->attributes; // the attributes
      }