ChatGPT解决这个技术问题 Extra ChatGPT

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:

[{"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.


H
Halfacht

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

You can use the following approach.

$data = [
    ['user_id'=>'Coder 1', 'subject_id'=> 4096],
    ['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 within the $query variable.


Use the ->toArray() method on the object collection.
It does not insert the timestamps.
add 'created_at'=>date('Y-m-d H:i:s'), 'modified_at'=> date('Y-m-d H:i:s') into your array. source: stackoverflow.com/a/26569967/1316842
I wonder why Laravel doesn't have something like 'createMany' for this.
How do I retrieve the ids?
V
Vishal Varshney

using Eloquent

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

Model::insert($data);

insert is method of query builder. Accessor and mutators will not work with this insert
R
Rock Dial

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']);

I could be mistaken but isn't this version 8 only?