Home >Database >Mysql Tutorial >How Can I Efficiently Insert Multiple Rows into a Database Using Laravel's Eloquent or Query Builder?
Use Eloquent or Query Builder to efficiently insert multiple rows of data
When you need to insert an unknown number of multiple rows of data from a single query, you can use Laravel's Eloquent ORM or Query Builder to perform bulk insert operations, simplifying the process and improving efficiency.
Using the $query you provide, its data can be extracted into an associative array:
<code>$data = $query->toArray();</code>
Now you have an array containing multiple rows of data in a format suitable for bulk inserts.
Eloquent methods
To perform bulk inserts using Eloquent, use the following syntax:
<code>UserSubject::insert($data); // 调用 Eloquent mutator,包括时间戳</code>
This method accepts an array of associative arrays as a parameter and performs an insertion operation for each row.
Query Builder method
Alternatively, if you prefer to use the Query Builder approach, you can use the following syntax:
<code>DB::table('target_table')->insert($data); // 不调用 mutator</code>
Query Builder method inserts data directly into the specified table without calling the Eloquent mutator.
By using any of the above methods, you can efficiently insert multiple rows into a new table from a single query, ensuring you get the desired data structure.
The above is the detailed content of How Can I Efficiently Insert Multiple Rows into a Database Using Laravel's Eloquent or Query Builder?. For more information, please follow other related articles on the PHP Chinese website!