我有一个自定义查询,它从旧系统中获取数据并将其映射到新系统中的模型.查询如下所示:
$companies = DB :: connection(‘legacy’) – > select(“…”);
由于它是大量数据,我想使用Eloquent的块功能(只是从他们的文档中复制的示例代码):
User::chunk(200,function($users) { foreach ($users as $user) { // } });
我该如何实现?
编辑:我的代码现在看起来像这样,导致没有响应:
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(); } });
尝试这样的事情:
原文链接:https://www.f2er.com/laravel/132433.html<?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的Paginator所做的事情而没有额外的开销.