search
HomePHP FrameworkLaravelLearn about batch insert operations in laravel framework in two minutes

Learn about batch insert operations in laravel framework in two minutes

In daily development, there are quite a lot of batch insertion operations. I remember a long time ago, I was still writing sql insertion in a loop, but was pressed to the ground and rubbed by the project manager. Well, performance is fine when not in use. If performance becomes a bottleneck, then code optimization and database optimization will bear the brunt.

Without further ado, let’s open the code!

1. First, check the laravel5.1 manual

Learn about batch insert operations in laravel framework in two minutes

##As can be seen from the picture: laravel provides the insert method of inserting an array, and That is to say, we can directly insert($array) to implement the batch insertion operation

2. First use laravel's get() query to obtain the array object, and then batch insert the operation

$ret = [];
    $create_red = new create_red();
    foreach($arr3 as $v){
      $delayDays = $v->delayDays;
      $workDays = $v->workDays;
      //获取当天时间戳的0点
      $now = strtotime(date('Y-m-d',time()));  ;
      $start = $now + $delayDays*86400;
      $start_at = date("Y-m-d H:i:s",$start);
      $end =  $now + $delayDays*86400 + $workDays*86400;
      $end_at = date('Y-m-d H:i:s',$end);
      $created_at = date("Y-m-d H:i:s",$now);
      $ret[] = [
        'uid'=>$uid,
        'status'=>1,
        'title'=>$v->title,
        'desc'=>$v->desc,
        'discount'=>$v->discount,
        'minprice'=>$v->minprice,
        'imgurl'=>$v->imgurl,
        'start_at'=>$start_at,
        'end_at'=>$end_at,
      ];
    }
    //往数据库批量插入数据
    $result = $create_red::insert($ret);
    if(!$result){
      DB::rollBack();
      return MyResponse::error(9006,'兑换优惠券失败');
    }

1. Create a new empty array

2. Loop through the

arr, and and loop towards emptyNumbergrouparr, and loop to the empty array4. Use the model::insert($array) method to insert in batches

5. The result is OK and the batch insertion is successful.

3. Batch insertion after generating redemption codes in batches

First enter the code:

 $num = 200;
    $codeArr = [];
    for($i=0;$i<$num;$i++){
      $code = EventCode::rand_str(8);
      $codeArr[$i][&#39;code&#39;] = $code;
    }
    /*var_dump($codeArr);
    exit;*/
    $event = new EventCode();
    $arr = $event::insert($codeArr);
    if(!$arr){
      return MyResponse::error(&#39;生成兑换码失败&#39;);
    }

1. Create a new empty Array 2. Loop to generate the redemption code and write it into the array

3. Print the array. After the array is displayed normally, use the insert() method to insert

4. Here The insertion effect is also OK. The efficiency of using laravel's own insert to achieve batch insertion is still acceptable. However, the number of insertions is small and the performance has not been specifically implemented. If I find anything in the future, I will write it down and share it with everyone.

Recommended tutorial: "

Laravel

"

The above is the detailed content of Learn about batch insert operations in laravel framework in two minutes. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:CSDN. If there is any infringement, please contact admin@php.cn delete
Using Laravel Blade for Frontend Templating in Full-Stack ProjectsUsing Laravel Blade for Frontend Templating in Full-Stack ProjectsMay 01, 2025 am 12:24 AM

LaravelBladeenhancesfrontendtemplatinginfull-stackprojectsbyofferingcleansyntaxandpowerfulfeatures.1)Itallowsforeasyvariabledisplayandcontrolstructures.2)Bladesupportscreatingandreusingcomponents,aidinginmanagingcomplexUIs.3)Itefficientlyhandleslayou

Building a Full-Stack Application with Laravel: A Practical TutorialBuilding a Full-Stack Application with Laravel: A Practical TutorialMay 01, 2025 am 12:23 AM

Laravelisidealforfull-stackapplicationsduetoitselegantsyntax,comprehensiveecosystem,andpowerfulfeatures.1)UseEloquentORMforintuitivebackenddatamanipulation,butavoidN 1queryissues.2)EmployBladetemplatingforcleanfrontendviews,beingcautiousofoverusing@i

What kind of tools did you use for the remote role to stay connected?What kind of tools did you use for the remote role to stay connected?May 01, 2025 am 12:21 AM

Forremotework,IuseZoomforvideocalls,Slackformessaging,Trelloforprojectmanagement,andGitHubforcodecollaboration.1)Zoomisreliableforlargemeetingsbuthastimelimitsonthefreeversion.2)Slackintegrateswellwithothertoolsbutcanleadtonotificationoverload.3)Trel

Remote Access and Screen Sharing: Bridging the Distance for Technical SupportRemote Access and Screen Sharing: Bridging the Distance for Technical SupportMay 01, 2025 am 12:07 AM

Remoteaccessandscreensharingworkbyestablishingasecure,real-timeconnectionbetweencomputersusingprotocolslikeRDP,VNC,orproprietarysolutions.Bestpracticesinclude:1)Buildingtrustthroughclearcommunication,2)Ensuringsecuritywithstrongencryptionandup-to-dat

Is it worth upgrading to the latest Laravel version?Is it worth upgrading to the latest Laravel version?May 01, 2025 am 12:02 AM

Definitely worth considering upgrading to the latest Laravel version. 1) New features and improvements, such as anonymous migration, improve development efficiency and code quality. 2) Security improvement, and known vulnerabilities have been fixed. 3) Community support has been enhanced, providing more resources. 4) Compatibility needs to be evaluated to ensure smooth upgrades.

Laravel logs and error monitoring: Sentry and Bugsnag integrationLaravel logs and error monitoring: Sentry and Bugsnag integrationApr 30, 2025 pm 02:39 PM

Integrating Sentry and Bugsnag in Laravel can improve application stability and performance. 1. Add SentrySDK in composer.json. 2. Add Sentry service provider in config/app.php. 3. Configure SentryDSN in the .env file. 4. Add Sentry error report in App\Exceptions\Handler.php. 5. Use Sentry to catch and report exceptions and add additional context information. 6. Add Bugsnag error report in App\Exceptions\Handler.php. 7. Use Bugsnag monitoring

Why is Laravel still the preferred framework for PHP developers?Why is Laravel still the preferred framework for PHP developers?Apr 30, 2025 pm 02:36 PM

Laravel remains the preferred framework for PHP developers as it excels in development experience, community support and ecosystem. 1) Its elegant syntax and rich feature set, such as EloquentORM and Blade template engines, improve development efficiency and code readability. 2) The huge community provides rich resources and support. 3) Although the learning curve is steep and may lead to increased project complexity, Laravel can significantly improve application performance through reasonable configuration and optimization.

Laravel Live Chat Application: WebSocket and PusherLaravel Live Chat Application: WebSocket and PusherApr 30, 2025 pm 02:33 PM

Building a live chat application in Laravel requires using WebSocket and Pusher. The specific steps include: 1) Configure Pusher information in the .env file; 2) Set the broadcasting driver in the broadcasting.php file to Pusher; 3) Subscribe to the Pusher channel and listen to events using LaravelEcho; 4) Send messages through Pusher API; 5) Implement private channel and user authentication; 6) Perform performance optimization and debugging.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment