Home > Database > Mysql Tutorial > How Can I Efficiently Insert Multiple Rows into a Database Using Laravel's Eloquent or Query Builder?

How Can I Efficiently Insert Multiple Rows into a Database Using Laravel's Eloquent or Query Builder?

DDD
Release: 2025-01-12 20:21:49
Original
105 people have browsed it

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>
Copy after login

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>
Copy after login

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>
Copy after login

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!

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template