2016-12-02 7 views
0

Я создал несколько форм ввода, как показано ниже, и я хочу сохранить базу данных, проблема в том, что при использовании dd() отображаются только данные второй строки.Laravel вставить несколько форм ввода в базу данных

Как сохранить каждую строку в базе данных?

enter image description here

здесь мой Laravel контроллер

public function store(Request $request) 
{ 

     $input = Input::all(); 
     $condition = $input['service_id']; 
     foreach ($condition as $key => $condition) { 
      $detailorder = new DetailOrder; 
      $detailorder->serivce_id = $input['service_id'][$key]; 
      $detailorder->order_type = $input['order_type'][$key]; 
      $detailorder->select_plan = $input['select_plan'][$key]; 
      $detailorder->qty = $input['qty'][$key]; 
      $detailorder->unit_price = $input['unit_price'][$key]; 
      //$detailorder->mandays = $input['mandays'][$key]; 
      $detailorder->note = $input['note'][$key]; 
      } 
      dd($detailorder); 

} 

и вот мой стол сценарий, я использую JQuery, чтобы он создал

function getCorporateService(id){ 
    // get data and parsing to column 
    $.get("{{ url('salesorder/service')}}/"+id, function(data){ 
     console.log(id); 
     console.log(data); 

     $.each(data, function (index, element){ 
      $br = "<tr id='item'>"; 
      $br += "<td> <input class='input-small' type='text' id='order_identifier' name='order_identifier[]' readonly></td>"; 
      $br += "<td><input class='input-small' type='text' id='service_name["+id+"]' name='service_name[]' value='"+element.service_name+"' readonly>" 
         +"<input class='input-small' type='hidden' id='service_id["+id+"]' name='service_id[]' value='"+element.id+"' readonly></td>"; 
      $br += "<td><select id='order_type["+id+"]' name='order_type[]'> <option> - </option> <option value='add'>Add</option> <option value='change'>Change</option> <option value='cancel'>Cancel</option> </select></td>"; 
      $br += "<td><input class='input-small' type='text' id='select_plan["+id+"]' name='select_plan[]'></td>"; 
      $br += "<td><input class='input-mini' type='text' id='qty["+id+"]' name='qty[]' value='1' onChange='getTotalPrice("+id+")'></td>"; 
      $br += "<td><input class='input-small' type='text' id='unit_price["+id+"]' name='unit_price[]' onChange='getTotalPrice("+id+")'></td>"; 
      $br += "<td><input class='input-small' type='text' id='total_price["+id+"]' name='total_price[]' onChange='getTotalPrice("+id+")'></td>"; 
      $br += "<td><textarea class='input-small' id='notes["+id+"]' name='note[]'></textarea></td>"; 
      $br += "</tr>"; 

      $(".corporatesvc").append($br); 

     }); 
    }); 
} 

ответ

1

Я не знаю о вашей dd функции. В настоящее время проходит цикл и исчезает все, что вам старые заказы и передавая последним в вашем dd function, так что вам нужно сделать массив объектов и передать его в функцию, как,

$allOrders=array(); // make an array, for storing all detail order in it 
foreach ($condition as $key => $condition) { 
    $detailorder = new DetailOrder; 

    //you can use to ignore $key::=> $detailorder->serivce_id = $condition['service_id']; 

    $detailorder->serivce_id = $input['service_id'][$key]; 
    $detailorder->order_type = $input['order_type'][$key]; 
    $detailorder->select_plan = $input['select_plan'][$key]; 
    $detailorder->qty = $input['qty'][$key]; 
    $detailorder->unit_price = $input['unit_price'][$key]; 
    //$detailorder->mandays = $input['mandays'][$key]; 
    $detailorder->note = $input['note'][$key]; 
    $allOrders[]=$detailorder; 
} 
dd($allOrders); // pass it to the function 
+0

спасибо. теперь работает :) – rafitio

1

Проверьте следующую строку:

foreach ($condition as $key => $condition) { 
    $detailorder = new DetailOrder; 
    // here you are creating a new object on each iteration, means on each iteration new object overrides old one, that's why you are getting the last record only 
} 

Чтобы решить эту проблему, поставьте этот код создания объекта за пределы цикла и повторите попытку.

1

Вы можете вставить несколько пунктов с этим код:

DB::table('tablename')->insert($tableitems); 
2

В public function store(Request $request) добавьте строку, как показано ниже

public function store(Request $request) 
{ 

     $input = Input::all(); 
     $condition = $input['service_id']; 
     foreach ($condition as $key => $condition) { 
      $detailorder = new DetailOrder; 
      $detailorder->serivce_id = $input['service_id'][$key]; 
      $detailorder->order_type = $input['order_type'][$key]; 
      $detailorder->select_plan = $input['select_plan'][$key]; 
      $detailorder->qty = $input['qty'][$key]; 
      $detailorder->unit_price = $input['unit_price'][$key]; 
      //$detailorder->mandays = $input['mandays'][$key]; 
      $detailorder->note = $input['note'][$key]; 

      //for saving each DetailOrder to database 
      $detailorder->save(); 
      } 
} 

Обратите внимание, что здесь save() должен вызывается из цикла foreach для сохранения каждой строки в базе данных.

Учитывая, что ваш JavaScript работает исправно, вышеуказанная модификация сохранит данные каждой строки в вашей базе данных.