Fork me on GitHub

laravel-chunk-missing-half-the-results


只要从现在开始努力,最坏不过是大器晚成

Q

I have a problem with Laravel’s ORM Eloquent chunk() method. It misses some results. Here is a test query :

1
2
3
4
5
6
7
8
$destinataires = Destinataire::where('statut', '<', 3)
->where('tokenized_at', '<', $date_active)
->chunk($this->chunk, function ($destinataires) {
foreach($destinataires as $destinataire) {
$this->i++;
}
}
echo $this->i;

It gives 124838 results.
But :

1
2
3
4
$num_dest = Destinataire::where('statut', '<', 3)
->where('tokenized_at', '<', $date_active)
->count();
echo $num_dest;

gives 249676, so just TWICE as the first code example.

A

Use chunkById() instead of chunk().

When updating or deleting records inside the chunk callback, any changes to the primary key or foreign keys could affect the chunk query. This could potentially result in records not being included in the chunked results.

1
2
3
4
5
6
7
8
DB::table('users')->where('active', false)
->chunkById(100, function ($users) {
foreach ($users as $user) {
DB::table('users')
->where('id', $user->id)
->update(['active' => true]);
}
});

https://stackoverflow.com/questions/32700537/eloquent-chunk-missing-half-the-results

请我喝一个苹果味的美年达吧,谢谢!