Route::post('/orders/create', function(Request $request){ $data = $request->all(); if(!Orders::where('orderNo', '=', $data['orderNo'])->exists()){ $order = 訂單::創(chuàng)建([ “姓名” => $data[“名稱”], “數(shù)量” => $data[“數(shù)量”], “選項(xiàng)” => $data[“選項(xiàng)”], “訂單號(hào)” => $data[“訂單號(hào)”], “用戶ID” => $data[“用戶ID”], “價(jià)格” => $data[“價(jià)格”], “費(fèi)用” => $data[“費(fèi)用”], “日期” => $data[“日期”], ]); if(空($order->id)){ 返回 [ “成功” =>錯(cuò)誤的, “響應(yīng)” => [ “錯(cuò)誤” => “發(fā)生了異常錯(cuò)誤” ] ]; } 別的 { 返回 [ “成功” =>真的, “響應(yīng)” => [ “訂單” => $訂單 ] ]; } } 別的 { 返回 [ “成功” =>錯(cuò)誤的, “響應(yīng)” => [ “錯(cuò)誤” => “庫存項(xiàng)目已存在” ] ]; } });</pre> <p>我的訂單模型文件:</p>class Orders 擴(kuò)展 Model { 使用 HasFactory; 受保護(hù)的$可填充= [ '產(chǎn)品', '數(shù)量', '選項(xiàng)', '訂單號(hào)', '用戶身份', '價(jià)格', '費(fèi)用', '日期', ]; 公共函數(shù)乘積 (){ 返回 $this->hasMany(Product::class); } }</pre> <p>如果您能幫助我解決這個(gè)問題,我將不勝感激,因?yàn)槲乙呀?jīng)為此苦苦掙扎了一段時(shí)間。</p>
我設(shè)法弄清楚了。我 console.log(this.cart.name) 并發(fā)現(xiàn)它是“未定義”。經(jīng)過進(jìn)一步調(diào)查,我發(fā)現(xiàn)原因是 state.cart 是一個(gè)對(duì)象數(shù)組,而不僅僅是一個(gè)對(duì)象。當(dāng)然,原因是購物車中的每個(gè)單獨(dú)的商品都應(yīng)該是它自己的對(duì)象。所以我的解決方案是:
for(let i = 0; i <= this.cart.length - 1; i++){ try { const order = await APIController.CreateOrder(this.cart[i].name, this.cart[i].qty, this.cart[i].option, this.cart[i].price, this.orderNum, this.cart[i].fee, this.cart[i].date, this.id); if(order){ this.clearCart(); } } catch (error){ console.log(error); } }
分解:由于 this.cart 是一個(gè)數(shù)組而不是一個(gè)對(duì)象,我必須首先使用 for 循環(huán)來獲取購物車中每個(gè)項(xiàng)目的索引,然后調(diào)用將數(shù)據(jù)發(fā)布到數(shù)據(jù)庫的函數(shù)。