Home  >  Article  >  Database  >  How to Create Insert...Select Statements with Laravel: Eloquent and Query Builder Solutions?

How to Create Insert...Select Statements with Laravel: Eloquent and Query Builder Solutions?

Susan Sarandon
Susan SarandonOriginal
2024-11-01 02:20:28325browse

How to Create Insert...Select Statements with Laravel: Eloquent and Query Builder Solutions?

Create Insert... Select Statements in Laravel

Q: How do I create an Insert...Select statement using Laravel's Eloquent ORM or queries? I'm struggling to convert the following SQL syntax:

<code class="sql">Insert into Demand (Login, Name, ApptTime, Phone, Physician, Location, FormatName, FormatDate, FormatTime, ApptDate, FormatPhone, cellphone)
Select Login, Name, ApptTime, Phone, Physician, Location, FormatName, FormatDate, FormatTime, ApptDate, FormatPhone, cellphone from " . [dbname] . "
    Where " . $where_statement</code>

A: While there isn't a direct one-query approach in Laravel within most versions, there are alternative methods to achieve a similar result:

Method 1: Using Raw SQL and Binding Parameters

<code class="php">$select = User::where(...)->where(...)->select(['email', 'moneyOwing']);
$bindings = $select->getBindings();

$insertQuery = 'INSERT into user_debt_collection (email, dinero) ' . $select->toSql();

DB::insert($insertQuery, $bindings);</code>

Method 2: Using insertUsing() (Laravel 5.7 and above)

<code class="php">DB::table('user_debt_collection')->insertUsing(['email', 'dinero'], $select);</code>

Note: These methods allow you to reuse the existing SELECT statement's bindings and execute the INSERT statement separately.

The above is the detailed content of How to Create Insert...Select Statements with Laravel: Eloquent and Query Builder Solutions?. 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