簡體   English   中英

從Laravel插入JSON數組

[英]Inserting a JSON array from Laravel

我想知道如何通過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');

會發生什么,它只將最后一組值存儲到表中而不是所有值。 我提前感謝任何幫助和感謝。

把你的save()放在你的循環中。 此外,您應該在一個事務中執行它, 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();
});

你需要把$report_recipient->save(); 在你的foreach循環中。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM