Billy Billy - 1 year ago 106
SQL Question

How to insert multiple rows from a single 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:


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

1 |8 |9
2 |8 |2

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

Answer Source

It is really easy 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
DB::table('table')->insert($data); // Query Builder

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