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("...");
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)
{
//
}
});
How do I implement this?
Edit: 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();
}
});
The
chunk
feature is only available for Eloquent models and QueryBuilder requests, e.g.But it won't work for
DB::select('...')
request. You need to either use a QueryBuilder request, or use an underlying PDO object to query the database, e.g:None of these answers worked for me. I created my own function based on @deyes answer.
Usage
Please note that this a simple quick fix and your query probably has to be fairly simple as I'm using search-replace to build a count query and I'm just tacking on LIMIT X, Y to the end of the query but it works for me.
I believe you can use
chunk
on a query builder. E.g.Try using the orderBy clause:
Update: March 2018 a new function was added to the query builder class. It's possible to achieve the same now using
fromSub
:And to use a different connection start with
DB::connection('legacy')->query()
Old answer: Found this question by accident, but a little trick that might come handy in some cases.
The query laravel executes then goes like this:
This should work at least in Laravel 5.1. But I don't see a reason why it shouldn't work in 4+.
deyes's answer has a bug.
AS-IS
if 'legacy' table has 'id' column and there's 1,2,3,4,5 ... 100 numbered data.
TO-DO