How to Perform Bulk Inserts in Laravel Using Eloquent or Query Builder?

DDD
Release: 2024-11-21 06:06:09
Original
523 people have browsed it

How to Perform Bulk Inserts in Laravel Using Eloquent or Query Builder?

Performing Bulk Inserts with Eloquent or Fluent in Laravel

In Laravel, bulk inserting data is a breeze, and you can utilize either the Eloquent ORM or the fluent query builder to accomplish this.

Consider the following query:

$query = UserSubject::where('user_id', Auth::id())
                    ->select('subject_id')
                    ->get();
Copy after login

This produces the output:

[{"user_id":8,"subject_id":9},{"user_id":8,"subject_id":2}]
Copy after login

Your goal is to transfer this data into a separate table, resulting in a structure like:

ID | user_id | subject_id
1   | 8       | 9
2   | 8       | 2
Copy after login

To perform this bulk insert, you can employ one of the approaches outlined below:

Eloquent Approach:

$data = [
    ['user_id' => 8, 'subject_id' => 9],
    ['user_id' => 8, 'subject_id' => 2]
];

UserSubject::insert($data);
Copy after login

This method utilizes mutators and timestamps.

Query Builder Approach:

$data = [
    ['user_id' => 8, 'subject_id' => 9],
    ['user_id' => 8, 'subject_id' => 2]
];

DB::table('user_subject')->insert($data);
Copy after login

While this method is more direct, it doesn't invoke mutators.

The above is the detailed content of How to Perform Bulk Inserts in Laravel Using 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