首頁  >  文章  >  資料庫  >  如何在 Laravel 中使用 Insert...Select 將資料從一個表插入到另一個表?

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

Mary-Kate Olsen
Mary-Kate Olsen原創
2024-10-28 19:46:02959瀏覽

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中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn