Home >Database >Mysql Tutorial >How to Efficiently Perform Bulk Inserts with Laravel Eloquent and Query Builder?

How to Efficiently Perform Bulk Inserts with Laravel Eloquent and Query Builder?

Linda Hamilton
Linda HamiltonOriginal
2025-01-12 20:17:42761browse

How to Efficiently Perform Bulk Inserts with Laravel Eloquent and Query Builder?

Use Laravel Eloquent/Fluent to batch insert multiple rows of data

This example requires inserting query result data into another table and converting the results into a specific format. The main challenge is handling potential changes in the number of rows in the results.

Use Laravel’s batch insert function

Luckily, Laravel’s Eloquent and query builder provide convenient bulk insert methods. You can utilize these methods to achieve the desired results:

  1. Eloquent method:

    <code class="language-php"> $insertData = collect($query->get())->map(function ($row) {
         return [
             'user_id'   => $row->user_id,
             'subject_id' => $row->subject_id,
         ];
     });
    
     Model::insert($insertData->toArray());</code>
  2. Query builder method:

    <code class="language-php"> $insertData = collect($query->get())->map(function ($row) {
         return [
             'user_id'   => $row->user_id,
             'subject_id' => $row->subject_id,
         ];
     });
    
     DB::table('new_table')->insert($insertData->toArray());</code>

In both cases, the $insertData variable contains the converted data in the required format. The insert method will handle bulk insert operations to the specified table. Note that in order to ensure that the insert method handles the data correctly, you need to convert $insertData to an array using the ->toArray() method.

The above is the detailed content of How to Efficiently Perform Bulk Inserts with Laravel Eloquent and Query Builder?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn