2017-05-05 112 views
1

我想以多種形式記錄設備,但始終會出現錯誤。 未定義指數:命名在Laravel中將數組數據發佈到數據庫中

public function EquipCheck(Request $request) { 
    $user = User::where('username', $request -> username) -> firstOrFail(); 
    if ($request -> token == $user -> token) { 
     $item_detail_id = CheckLog::where('user_id', $user -> id) -> orderBy('id', 'desc') -> first() -> item_detail_id; 
     $new_form = new Form; 
     $new_form -> item_detail_id = $item_detail_id; 
     $new_form -> user_id = User::where('username', $request -> username) -> firstOrFail() -> id; 
     $new_form -> created_time = Carbon::now() -> format('Y-m-d H:i:s'); 
     $new_form -> save(); 
     $form = Form::with('eqpt') -> where('item_detail_id', $item_detail_id) -> orderBy('created_time', 'desc') -> first(); 

     $data = $request -> eqpt; 
     $i = 0; 
     $sql = array(); 

     while($i < count($cyldata['serie'])){ 
      $sql[] = array(
       'form_id' => $form -> id, 
       'name' => $data['name'][$i], 
       'unit' => $data['unit'][$i], 
       'quantity' => $data['quantity'][$i], 
       'check_quantity' => $data['check_quantity'][$i], 
      ); 
      $i++; 
     } 

     DB::table('eqpt') -> insert($sql); 

     return "Success"; 
    } 
} 

當我使用下面的代碼,數據庫可被插入該陣列。

$dataSet[] = [ 
      'form_id' => $form -> id, 
      'name' => 'test', 
      'unit' => 'box', 
      'quantity' => 20, 
      'check_quantity' => 20, 
     ]; 

     DB::table('eqpt') -> insert($dataSet); 

This is post data.

+0

您是否嘗試過你設置後,檢查'$ data'變量?另外,$ cyldata ['serie']'被設置在哪裏? – jackel414

+0

如何從帖子數據重新創建數組? –

+0

你是否創建了dd($ data)?你能讓我們知道結果嗎? –

回答

2

$數據包含對象的陣列。 $ data ['name']引用該數組的屬性,而您應該訪問該數組中的對象的屬性。

更換

$sql[] = array(
    'form_id' => $form -> id, 
    'name' => $data['name'][$i], 
    'unit' => $data['unit'][$i], 
    'quantity' => $data['quantity'][$i], 
    'check_quantity' => $data['check_quantity'][$i], 
); 

$sql[] = array(
    'form_id' => $form -> id, 
    'name' => $data[$i]['name'], 
    'unit' => $data[$i]['unit'], 
    'quantity' => $data[$i]['quantity'], 
    'check_quantity' => $data[$i]['check_quantity'], 
); 
+0

良好的捕獲 - 我沒有看到,OP已轉置的關鍵。 – jackel414