首页  >  文章  >  数据库  >  如何在 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