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:
Utilize Model::insert($data); to insert multiple rows. This approach incorporates mutators, including timestamps.
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], //... ];
Inserting them using Eloquent:
Model::insert($data);
Inserting them using the Query Builder:
DB::table('table')->insert($data);
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3