Memahami 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) { // 处理行数据 });
<?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()); }); } }
untuk membuat koleksi malas: cursor()
<?php namespace App\Http\Controllers; use App\Models\Transaction; use Illuminate\Support\Facades\DB; class ReportController extends Controller { public function generateReport() { DB::transaction(function () { Transaction::cursor() ->filter(function ($transaction) { return $transaction->amount > 1000; }) ->each(function ($transaction) { // 处理每笔大额交易 $this->processHighValueTransaction($transaction); }); }); } }
Atas ialah kandungan terperinci Menguruskan dataset besar di Laravel dengan lazycollection. Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!