从Laravel插入JSON数组

时间:2016-05-17 21:45:04

标签: php json 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');

会发生什么,它只将最后一组值存储到表中而不是全部存储。我提前感谢任何帮助和感谢。

2 个答案:

答案 0 :(得分:2)

将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();
});

答案 1 :(得分:1)

您需要将$report_recipient->save();放入foreach循环中。