How to insert multiple rows from one query using eloquent / fluent

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 to copy the specified result to another table so that my table looks like this:

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

The problem is that $query can expect any number of rows, so I'm not sure how to iterate over an unknown number of rows.

+54
sql php eloquent laravel
Apr 18 '15 at 22:58
source share
2 answers

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

You can use the following approach.

 $data = array( array('user_id'=>'Coder 1', 'subject_id'=> 4096), array('user_id'=>'Coder 2', 'subject_id'=> 2048), //... ); Model::insert($data); // Eloquent approach DB::table('table')->insert($data); // Query Builder approach 

In your case, you already have the data in the $query variable.

+119
Apr 18 '15 at 23:14
source share

using eloquent

 $data = array( array('user_id'=>'Coder 1', 'subject_id'=> 4096), array('user_id'=>'Coder 2', 'subject_id'=> 2048), //... ); Model::insert($data); 
0
Jul 04 '17 at 14:33
source share



All Articles