Home  >  Article  >  Database  >  How to Insert Data from One Table to Another Using Insert...Select in Laravel?

How to Insert Data from One Table to Another Using Insert...Select in Laravel?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-10-28 19:46:02959browse

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn