如何在 Laravel 中使用 Insert...Select 將資料從一個表插入到另一個表?

Mary-Kate Olsen
發布: 2024-10-28 19:46:02
原創
958 人瀏覽過

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

在Laravel 中使用Insert...Select 插入資料

為了使用Insert...將資料從一個表格插入到另一個表格插入到另一個表格表... Laravel 中的Select 語句,您可以使用以下方法:

雖然Laravel 的Eloquent ORM 或查詢不直接支援Insert...Select 語句,但您可以利用底層資料庫連接來實現所需的結果。

<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 更新:

在Laravel 5.7.17 及更高版本中,您也可以使用insertUsing() 方法來實現類似的結果:

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

以上是如何在 Laravel 中使用 Insert...Select 將資料從一個表插入到另一個表?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!