Home > Database > Mysql Tutorial > body text

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

Mary-Kate Olsen
Release: 2024-10-28 19:46:02
Original
958 people have browsed it

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>
Copy after login

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>
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!