How Can I Insert Multiple Rows into a Database Using Eloquent or the Query Builder?

Susan Sarandon
Release: 2024-11-21 06:47:09
Original
668 people have browsed it

How Can I Insert Multiple Rows into a Database Using Eloquent or the Query Builder?

Insert Multiple Rows Simultaneously with Eloquent or Fluent

This inquiry explores how to insert multiple rows into a database using a single query within the Eloquent (or fluent) framework. The given example retrieves data using UserSubject::where('user_id', Auth::id())->select('subject_id')->get();. However, the desired output requires inserting this data into a separate table with a specific column structure.

Solution:

Bulk inserting data is conveniently facilitated by Eloquent or the query builder. Consider the following techniques:

  • Eloquent Approach:

Utilize Model::insert($data); to insert multiple rows. This approach incorporates mutators, including timestamps.

  • Query Builder Approach:

Employ DB::table('table')->insert($data); to insert rows without calling mutators.

Example:

Given an array of row data:

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

Inserting them using Eloquent:

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

Inserting them using the Query Builder:

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

The above is the detailed content of How Can I Insert Multiple Rows into a Database Using Eloquent or the 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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template