Home >Database >Mysql Tutorial >How to Insert Data from One Table to Another Using Insert...Select in Laravel?
Inserting Data Using Insert...Select in Laravel
In order to insert data from one table to another using the Insert...Select statement in Laravel, you can utilize the following approach:
While Laravel's Eloquent ORM or Queries do not support Insert...Select statements directly, you can leverage the underlying database connections to achieve the desired result.
<code class="php">/* Obtain the original select query and its bindings */ $select = User::where(...) ->where(...) ->whereIn(...) ->select(['email', 'moneyOwing']); $bindings = $select->getBindings(); /* Construct the insert query */ $insertQuery = 'INSERT INTO user_debt_collection (email, dinero) ' . $select->toSql(); /* Execute the insert query using the bindings */ \DB::insert($insertQuery, $bindings);</code>
Laravel 5.7 Update:
In Laravel 5.7.17 and later, you can also use the insertUsing() method to achieve a similar result:
<code class="php">DB::table('user_debt_collection')->insertUsing(['email', 'dinero'], $select);</code>
The above is the detailed content of How to Insert Data from One Table to Another Using Insert...Select in Laravel?. For more information, please follow other related articles on the PHP Chinese website!