Home > Database > Mysql Tutorial > body text

How to Create Insert...Select Statements with Laravel ORM?

Linda Hamilton
Release: 2024-11-05 05:25:02
Original
915 people have browsed it

How to Create Insert...Select Statements with Laravel ORM?

Creating Insert...Select Statements with Laravel ORM

Inserting records from another table into a new table can be achieved using an Insert...Select statement. In Laravel, you can utilize either the Eloquent ORM or raw SQL queries to accomplish this task.

Laravel Eloquent's Column Binding

Using Laravel's Eloquent ORM, you can take advantage of the getBindings() method to obtain the binding parameters for a previously constructed Select query. This allows you to reuse the already prepared statement.

<code class="php"><?php

// Create the Select query
$select = User::where(...)
    ->where(...)
    ->whereIn(...)
    ->select(['email', 'moneyOwing']);

// Get the binding parameters
$bindings = $select->getBindings();

// Construct the Insert query
$insertQuery = 'INSERT INTO user_debt_collection (email, dinero) ' . $select->toSql();

// Execute the Insert query using the bound parameters
DB::insert($insertQuery, $bindings);</code>
Copy after login

Using Raw SQL Queries

Alternatively, you can use raw SQL queries to create Insert...Select statements directly.

<code class="php"><?php

$insertQuery = '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;

DB::insert($insertQuery);
Copy after login

Laravel 5.7 and Later

For Laravel 5.7 and later, the insertUsing() method can be utilized to simplify the process.

<code class="php"><?php

DB::table('user_debt_collection')->insertUsing(['email', 'dinero'], $select);</code>
Copy after login

The above is the detailed content of How to Create Insert...Select Statements with Laravel ORM?. 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!