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!