How to chunk results from a custom query in Laravel(如何在 Laravel 中对自定义查询的结果进行分块)
问题描述
我有一个自定义查询,它从旧系统中获取数据并将其映射到新系统中的模型.查询如下所示:
I have a custom query that grabs data from the old system and maps it to models in the new system. The query looks like this:
$companies = DB::connection('legacy')->select("...");
由于数据量很大,我想使用 Eloquent 的块功能(只是从他们的文档中复制的示例代码):
And since it's a lot of data, I'd like to use Eloquent's chunk feature (just sample code copied from their docs):
User::chunk(200, function($users)
{
foreach ($users as $user)
{
//
}
});
我该如何实施?
我的代码现在看起来像这样,导致没有响应:
My code now looks like this, which results in no response:
DB::connection('legacy')->select("SELECT * FROM companies")->chunk(200, function($companies) {
foreach ($companies as $company) {
// dd($company);
$entity = Entity::firstOrNew(['external_id' => $company->companyKey]);
$entity->name = $company->companyName;
$entity->save();
}
});
推荐答案
试试这个:
<?php
$max = 100;
$total = DB::connection('legacy')->select("...")->count();
$pages = ceil($total / $max);
for ($i = 1; $i < ($pages + 1); $i++) {
$offset = (($i - 1) * $max);
$start = ($offset == 0 ? 0 : ($offset + 1));
$legacy = DB::connection('legacy')->select("...")->skip($start)->take($max)->get();
/* Do stuff. */
}
基本上复制了 Laravel 的分页器所做的事情,而没有额外的开销.
Basically duplicates what Laravel's Paginator does without the extra overhead.
这篇关于如何在 Laravel 中对自定义查询的结果进行分块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何在 Laravel 中对自定义查询的结果进行分块
- 如何使用 Google API 在团队云端硬盘中创建文件夹? 2022-01-01
- 覆盖 Magento 社区模块控制器的问题 2022-01-01
- openssl_digest vs hash vs hash_hmac?盐与盐的区别HMAC? 2022-01-01
- 如何从数据库中获取数据以在 laravel 中查看页面? 2022-01-01
- Oracle 即时客户端 DYLD_LIBRARY_PATH 错误 2022-01-01
- Laravel 5:Model.php 中的 MassAssignmentException 2021-01-01
- 使用 GD 和 libjpeg 支持编译 PHP 2022-01-01
- PHP foreach() 与数组中的数组? 2022-01-01
- 如何在 Symfony2 中正确使用 webSockets 2021-01-01
- PHP - if 语句中的倒序 2021-01-01