如何在 Laravel 中使用 `Insert...Select` 高效插入数据?

Barbara Streisand
发布: 2024-10-28 12:55:02
原创
476 人浏览过

How to Efficiently Insert Data Using `Insert... Select` in Laravel?

Laravel 中使用 Insert...Select 高效插入数据

Laravel 的查询转换

要将提供的 SQL 查询转换为 Laravel 表达式,了解 Laravel 5.6 及更早版本缺乏对 Insert...Select 操作的直接支持至关重要。这意味着直接转换是不可能的。

Laravel 中的替代方法

但是,有一个解决方法可以让您实现所需的结果。您可以将其分为两个步骤,而不是尝试单个查询:

  1. 利用 Laravel 的 QueryBuilder 构建一个检索必要数据的 Select 查询。使用 getBindings() 方法提取绑定参数。
  2. 使用原始 SQL 查询,使用步骤 1 中检索到的数据执行插入。绑定从 getBindings() 获取的绑定参数。

示例代码:

<code class="php">// Step 1: Generate the Select query
$select = User::where(...)
                  ->where(...)
                  ->whereIn(...)
                  ->select(array('email','moneyOwing'));

// Step 2: Get binding parameters
$bindings = $select->getBindings();

// Step 3: Construct raw SQL insert query
$insertQuery = 'INSERT into user_debt_collection (email,dinero) '
                . $select->toSql();

// Step 4: Execute the insert
\DB::insert($insertQuery, $bindings);</code>
登录后复制

Laravel 5.7 更新

Laravel 5.7 引入了 ->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学习者快速成长!