select([ 'id', 'date', 'value', ]) ->where('id', '>', 0) ->chunkById(1000, function ($transactions) { $items = []; /** @var Collection $transactions */ foreach ($transactions as $transaction) { $transaction->date = Carbon::now()->subDays(random_int(1, 3)); $transaction->value = 10 + random_int(0, 10); $items[] = [ 'id' => $transaction->id, 'date' => $transaction->date, 'value' => $transaction->value, ]; } $withs = []; $unions = []; foreach ($items as $key => $item) { $withs[] = vsprintf('u%s as (update transactions set value = %s where id = %s returning null)', [ $key, $item['value'], $item['id'], ]); $unions[] = vsprintf('u%s', [ $key ]); } $withs = implode(', ', $withs); $unions = implode(', ', $unions); $sql = "with $withs, uall as (select * from $unions) select * from uall"; DB::statement($sql); }); } }