Home > Backend Development > PHP Tutorial > How to Efficiently Insert Multiple Rows Using Eloquent or Query Builder in Laravel?

How to Efficiently Insert Multiple Rows Using Eloquent or Query Builder in Laravel?

Mary-Kate Olsen
Release: 2024-11-20 01:10:03
Original
800 people have browsed it

How to Efficiently Insert Multiple Rows Using Eloquent or Query Builder in Laravel?

Inserting Multiple Rows with Eloquent/Fluent

You want to insert multiple rows into another table based on a query that retrieves data from a specific table. Let's understand how this can be achieved using Eloquent or the query builder.

To bulk insert data using Eloquent:

$data = [
    ['user_id' => 'Coder 1', 'subject_id' => 4096],
    ['user_id' => 'Coder 2', 'subject_id' => 2048],
    // ...
];

Model::insert($data); // Calls mutators including timestamps
Copy after login

Alternatively, you can use the query builder:

DB::table('table')->insert($data); // Does not call mutators
Copy after login

In your case, you can modify the $query to retrieve the desired data and then insert it into the other table using one of the above methods.

Remember that you can dynamically determine the number of rows in $query using:

$rowCount = count($query);
Copy after login

This information can help you iterate through the rows if necessary.

The above is the detailed content of How to Efficiently Insert Multiple Rows Using Eloquent or Query Builder in Laravel?. For more information, please follow other related articles on the PHP Chinese website!

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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template