2016-05-17 2 views
1

Laravelを使用して配列値をデータベースに挿入する方法を知りたいと思います。 JSONのサンプルはここにある:LaravelからJSON配列を挿入する

[{"rid":"252","recipient_id":"1","email_type":"Body","to_cc_bcc":"to","start_dte":"2016-05-18","end_dte":""},{"rid":"252","recipient_id":"5","email_type":"Body","to_cc_bcc":"to","start_dte":"2016-05-18","end_dte":""}] 

そして、このような保存のための私のコントローラはこれです:

public function store() 
    { 
     // validate 
     // read more on validation at http://laravel.com/docs/validation 
     $rules = array(
      'name'  => 'required', 
     ); 
     $validator = Validator::make(Input::all(), $rules); 

     // process the login 
     if ($validator->fails()) { 
      return Redirect::to('reports') 
       ->withErrors($validator) 
       ->withInput(Input::except('password')); 
     } else { 
      //Dump Recipient array 
      $cleanRecipients = json_decode(Input::get('test'), true); 
       foreach($cleanRecipients AS $value) 
        { 
          $report_recipient = new ReportRecipients; 
          $report_recipient->recipient_id  = $value['recipient_id']; 
          $report_recipient->rid  = $value['rid']; 
          $report_recipient->email_type = $value['email_type']; 
          $report_recipient->to_cc_bcc = $value['to_cc_bcc']; 
          $report_recipient->start_dte = !empty($value['start_dte']) ? $value['start_dte'] : null; 
          $report_recipient->end_dte = !empty($value['end_dte']) ? $value['end_dte'] : null; 

        } 
         $report_recipient->save(); 

      // redirect 
      Session::flash('message', 'Report was Successfully Saved!'); 
      return Redirect::to('reports'); 

何が起こるかというと、それだけでテーブルに値の最後のセットを格納していないということですそれらのすべて。私はどんな助けと感謝を前もって感謝します。

答えて

1

$report_recipient->save();をforeachループの内側に配置する必要があります。

+1

愚かな私のコースです。もっとコーヒー..私はこの回答を5分後にチェックします。 :Dヒープありがとう – Odinovsky

2

ループ内にsave()を配置します。また、1つのトランザクションでそれをatomicにする必要があります。

\DB::transaction(function() use($cleanRecipients) { 
    foreach($cleanRecipients AS $value) { 
     $report_recipient = new ReportRecipients; 
     $report_recipient->recipient_id  = $value['recipient_id']; 
     $report_recipient->rid  = $value['rid']; 
     $report_recipient->email_type = $value['email_type']; 
     $report_recipient->to_cc_bcc = $value['to_cc_bcc']; 
     $report_recipient->start_dte = !empty($value['start_dte']) ? $value['start_dte'] : null; 
     $report_recipient->end_dte = !empty($value['end_dte']) ? $value['end_dte'] : null; 
     $report_recipient->save(); 
}); 
+0

チップをありがとう..私は後でDBに関数を作成します。 – Odinovsky

+0

Laravelにはすでにこの機能があります。そのまま使用してください。 –

関連する問題