ホームページ >バックエンド開発 >PHPチュートリアル >LazyCollectionを使用してLaravelの大規模なデータセットの管理
lazycollection
use Illuminate\Support\LazyCollection; LazyCollection::make(function () { $handle = fopen('data.csv', 'r'); while (($row = fgets($handle)) !== false) { yield str_getcsv($row); } })->each(function ($row) { // 处理行数据 });lazycollectionの例
この方法を使用すると、
を使用できます<?php namespace App\Services; use App\Models\TransactionLog; use Illuminate\Support\LazyCollection; class TransactionProcessor { public function processLogs(string $filename) { return LazyCollection::make(function () use ($filename) { $handle = fopen($filename, 'r'); while (($line = fgets($handle)) !== false) { yield json_decode($line, true); } }) ->map(function ($log) { return [ 'transaction_id' => $log['id'], 'amount' => $log['amount'], 'status' => $log['status'], 'processed_at' => $log['timestamp'] ]; }) ->filter(function ($log) { return $log['status'] === 'completed'; }) ->chunk(500) ->each(function ($chunk) { TransactionLog::insert($chunk->all()); }); } }
line
でログファイルを読み取ります以上がLazyCollectionを使用してLaravelの大規模なデータセットの管理の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。