laravel如何实现批量插入

Posted 花衣终会凋零,但愿余香缠绕指间

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了laravel如何实现批量插入相关的知识,希望对你有一定的参考价值。

1.自己写的做个记录

try {
            $str  = ‘[{"pageid":"270"},{"que":[{"title":"sad","type":"1","option_a":"sad","option_b":"sad","option_c":"dad","option_d":"ad","option_e":"d","option_f":"da","option_g":"sda","option_h":"d","answer":"sdad"},{"title":"sdaf","type":"1","option_a":"sfa","option_b":"fa","option_c":"da","option_d":"d","option_e":"d","option_f":"dd","option_g":"ad","option_h":"add","answer":"ad"},{"title":"wedwq","type":"1","option_a":"ea","option_b":"aaas","option_c":"ssssdas","option_d":"ad","option_e":"ad","option_f":"adad","option_g":"wdqd","option_h":"ws","answer":"ada"},{"title":"dwq","type":"1","option_a":"ad","option_b":"ad","option_c":"dad","option_d":"dad","option_e":"ad","option_f":"dw","option_g":"ad","option_h":"sad","answer":"d"},{"title":"af","type":"1","option_a":"sad","option_b":"a","option_c":"af","option_d":"saf","option_e":"asfdf","option_f":"da","option_g":"fs","option_h":"dasf","answer":"afa"}]}]‘;
            $info = json_decode($str);
            $arr = $info[1];
            $value=‘‘;
            foreach ($arr as $k=>$value) {
                $value=$value;
            }
            $pageid=$info[0]->pageid;
            foreach ($value as  $info){

                $arr1 = [
                    ‘title‘ => $info->title,//题目
                    ‘type‘ => $info->type,//题目类型
                    ‘option_a‘ => $info->option_a,//A
                    ‘option_b‘ => $info->option_b,//B
                    ‘option_c‘ => $info->option_c,//C
                    ‘option_d‘ => $info->option_d,//D
                    ‘option_e‘ => $info->option_e,//E
                    ‘option_f‘ => $info->option_f,//F
                    ‘option_g‘ => $info->option_g,//G
                    ‘option_h‘ => $info->option_h,//H
                    ‘answer‘ => $info->answer,//正确答案
                    ‘pageid‘=>$pageid,
                ];
                DB::table(‘v‘)->insert($arr1);

            }



        } catch (Exception $exception) {
            $exception->getMessage();
        }

 

以上是关于laravel如何实现批量插入的主要内容,如果未能解决你的问题,请参考以下文章

PHP框架 Laravel Eloquent ORM 批量插入数据,怎么实现

如何使用 Laravel 4.2 在单个查询(不是 for 查询循环)中批量插入或更新

Laravel 5.2 中的批量插入

Laravel 5.8 有条件地插入 sql 片段

laravel 5.6批量插入json数据

php实现mysql百万级数据插入,耗时10s左右