How to insert multiple rows from a single query using eloquent/fluent
Asked Answered
E

3

227

I have the following query:

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

and as expected I get the following result:

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

Is there a way of copying the above result into another table so that my table looks like this?

ID|user_id|subject_id
1 |8      |9
2 |8      |2

The problem I have is that the $query can expect any number of rows and so im unsure how to iterate through an unknown number of rows.

Eugenieeugenio answered 18/4, 2015 at 22:58 Comment(1)
in case anyone still needs it: github.com/laravel/framework/issues/1295#issuecomment-193025045Espy
C
447

It is really easy to do a bulk insert in Laravel using Eloquent or the query builder.

You can use one of the following techniques.

$data = [
    ['user_id'=>'Coder 1', 'subject_id'=> 4096],
    ['user_id'=>'Coder 2', 'subject_id'=> 2048],
    //...
];
  1. Eloquent approach:
Model::insert($data); // calls mutators including timestamps
  1. Query Builder approach:
DB::table('table')->insert($data); // does not call mutators
Casias answered 18/4, 2015 at 23:14 Comment(15)
I've tried that but unfortunately it's recognising my result as an object and not an arrayEugenieeugenio
Use the ->toArray() method on the object collection.Casias
It does not insert the timestamps.Chanukah
add 'created_at'=>date('Y-m-d H:i:s'), 'modified_at'=> date('Y-m-d H:i:s') into your array. source: https://mcmap.net/q/117027/-bulk-insertion-in-laravel-using-eloquent-ormCrowded
I wonder why Laravel doesn't have something like 'createMany' for this.Embroideress
I believe this approach will not trigger on_save and on_create event handlers declared it the "boot" method.Speech
@JoeriShoeby the OP wanted to do a batch INSERT. The HasOneMany::saveMany() doesn't do that. Eloquent sources are self-explainatoryDivider
What if i have an array like this ` $array = ["54928328", "Carrie","Swift"]; ` ?Subdebutante
How do I retrieve the ids?Fishhook
This technique is not inserting the created date. What should i do to insert created data with it? @KreshnikHasanajHypolimnion
@Fishhook Not a very Eloquent solution, but you could create a insertGetIds method, that just iterates over each element in the array of arrays and calls insertGetId and pushes that ID to an array, and then return that array of IDs.Liturgy
i tried ->toArray() as well but still it considers the collection as object. ``` $data =DB::table(DB::raw('users'))->select('name','id','email')->where('name','like','Abdulh%')->orderBy('id')->get(); ``` DB::table('staff')->insert($data);Patchy
what to do when my array size is bigger than 10 thousands?Eczema
In this case of multiple records insertion, can i add a condition which checks if the id field value already exists in db table then that record will not be inserted. Please help. Eloquent updateOrCreate method works only for 1 record.Curtsy
This is the most applicable answer! How do we put this in DB:transaction?Goddamn
A
37

using Eloquent

$data = array(
    array('user_id'=>'Coder 1', 'subject_id'=> 4096),
    array('user_id'=>'Coder 2', 'subject_id'=> 2048),
    //...
);

Model::insert($data);
Antagonism answered 4/7, 2017 at 14:33 Comment(1)
insert is method of query builder. Accessor and mutators will not work with this insertJacy
E
8

It is really easy to do a bulk insert in Laravel with or without the query builder. You can use the following official approach.

Entity::upsert([
    ['name' => 'Pierre Yem Mback', 'city' => 'Eseka', 'salary' => 10000000],
    ['name' => 'Dial rock 360', 'city' => 'Yaounde', 'salary' => 20000000],
    ['name' => 'Ndibou La Menace', 'city' => 'Dakar', 'salary' => 40000000]
], ['name', 'city'], ['salary']);
Electroanalysis answered 18/12, 2020 at 14:19 Comment(3)
I could be mistaken but isn't this version 8 only?Dorado
laravel doc on upsert = update or insert.Berezina
github.com/laravel/framework/discussions/38938 this is one of the issue you'd face.Slackjawed

© 2022 - 2024 — McMap. All rights reserved.