Home >Database >Mysql Tutorial >How Can I Insert Multiple Rows into a Database Table with a Single Eloquent Query in Laravel?
Handling large datasets often involves inserting numerous rows into database tables. Manually processing each row can be inefficient. Laravel's Eloquent ORM and query builder provide elegant solutions for bulk inserts, significantly improving performance.
For inserting data from a query result set while preserving the row structure, a bulk insert is ideal. Eloquent offers a straightforward method:
<code class="language-php">$data = $query->select(['user_id', 'subject_id'])->get()->toArray(); Model::insert($data);</code>
Note the addition of toArray()
. This is crucial for ensuring the data is in the correct format for the insert
method.
Alternatively, the query builder provides a similar function:
<code class="language-php">DB::table('table_name')->insert($data);</code>
Remember that Eloquent's insert
method triggers model mutators (including timestamps). If you need to bypass these, the query builder offers more direct control.
Both methods efficiently insert multiple rows with a single database query, regardless of the size of the $data
array, making them far more efficient than iterative insertions.
The above is the detailed content of How Can I Insert Multiple Rows into a Database Table with a Single Eloquent Query in Laravel?. For more information, please follow other related articles on the PHP Chinese website!