2017-06-22 62 views
0

我使用Angular2我的前端和laravel我的後臺數據,我有將數據保存到數據庫如何解析在後端

每個在Order[](前prodName鍵的麻煩, prodDesc)是在數據庫中的列名,所以我試圖循環請求和保存數據,但它不工作一樣

public function Order(Request $request) { 
    $input = $request->all(); 
    $order = new Order; 

    foreach ($input as $key => $value) { 
     if (array_key_exists($key, $input) && !empty($value)) { 
     $order->$key = $value; 
    } 
    } 
} 
if($order->save()) { 
    return response()->json(['order' => $order], 201); 
} 

order.interface.ts

export interface Order { 
    prodName: string; 
    prodDesc: string; 
} 

添加項目到訂單

addToOrder.component.ts

orders = [] as Order[]; 

saveItem(): void { 
    this.orders.push({prodName: this.prodName, prodDesc: this.prodDesc}); 
    this.dataService.save(this.orders).then(() => { 
    this.navCtrl.pop(Search); 
    }); 
} 

如何每個項目都存儲在存儲

order.storage.ts

save(data : Order[]): Promise<any> { 
    return this.getData().then((products: any[]) => { 
    if (products) { 
    products = products.concat(data); 
    return this.storage.set('products', products); 
    } 
    return this.storage.set('products', data); 
    }); 
} 

我如何找回從存儲

order.compo順序nent.ts

private order = [] as Order[]; 

constructor(public dataService: OrderStorage, public OrderService: OrderService) { 

    this.dataService.getData().then((products) => { 
    if (products) { 
    this.order = products; 
    } 
    }); 
} 

onSubmit() { 
    this.OrderService.submit(this.order) 
    .subscribe(); 
} 

的數據發佈到後端

order.service.ts

submit(order: Order[]): Observable<any> { 
    return this.http.post(localapi.app, order) 
    .map(
     (response: Response) => {}); 
} 

order數據的結構被髮送

enter image description here

檢索數據在後臺

public function Order(Request $request) { 
    $input = $request->all(); 
    var_dump($input); 
} 

後續代碼var_dump輸出

enter image description here

回答

1

它實際上foreach ($input as $key => $arr),那麼你可以使用你的循環:

foreach ($input as $arr) { 
    foreach ($arr as $key => $value) { 
     if (array_key_exists($key, $arr) && !empty($value)) { 
      $order->$key = $value; 
     } 
    } 
} 

第一組的元素,你會在你的循環遇到的是數組,那麼你可以循環你的數組屬性。

+0

它仍然無法正常工作。它說'prodName'沒有默認值 – ghan

+0

好吧,我想通了不得不改變'$ input'到'$ arr'在這樣的三線'(array_key_exists($鍵,$ ARR))'但現在它只是保存一條記錄 – ghan

+0

@ghan Aye,複製粘貼問題! – Ohgodwhy