Laravel内存不足

我试图将我的数据导出到Excel表,但我得到的错误:

Connection.php中的FatalErrorException第321行:允许的内存大小为134217728个字节已耗尽(试图分配196605个字节)

我知道我可以刚刚达到PHP的内存限制,但我想明白为什么我的代码占用这么多的内存。

我的代码:

public function exportExcel() { $datum = date("dmY"); Excel::create('Sales export '.$datum, function($excel) { $datum = date("dmY"); // Chain the setters $excel->setCreator('some name') ->setCompany('some company') ->setDescription('sales export.') ->setTitle('Salesexport '.$datum); $excel->sheet('sales '.$datum, function($sheet) { $orders = Order::orderBy('created_at','desc')->get(); $sheet->appendRow(array( "merk","product","artikel nr","categorie","collectie","maat","omschrijving","inkoopprijs","verkoopprijs","prijs betaald","aantal verkocht","verkocht aan", "totaal","dag","maand","jaar","kwartaal","reseller","verkoper","bestel naam" )); foreach($orders as $order) { foreach($order->products as $p) { $sizeLink = $p->productSize; $productLink = $sizeLink->product; // Append row as very last $sheet->appendRow(array( $productLink->brand->name, $productLink->name, $productLink->artnr, $productLink->category->name, $productLink->collection->name, $sizeLink->size->name, $productLink->desciption, number_format((float) $productLink->price_buy_in, 2, ',', ''), number_format((float) $productLink->price, 2, ',', ''), number_format((float) $p->price, 2, ',', ''), $p->quantity, //geboekt aantal $order->billingname . $order->billingnamelast, number_format((float) $p->quantity * $p->price, 2, ',', ''), // totaal kosten //number_format((float) ($p->quantity * $p->price - $p->quantity * $p->price_buy_in), 2, ',', ''), // winst inkoop-verkoop date("d",strtotime($order->created_at)), date("n",strtotime($order->created_at)), date("Y",strtotime($order->created_at)), ceil(date("m",strtotime($order->created_at))/3), $order->reseller->name, $order->creator, $order->name, )); } } // Auto filter for entire sheet $sheet->setAutoFilter(); $sheet->freezeFirstRow(); // Set black background $sheet->row(1, function($row) { // call cell manipulation methods $row->setBackground('#cccccc'); $row->setFontWeight("bold"); }); $sheet->setColumnFormat(array( 'G' => \PHPExcel_Style_NumberFormat::FORMAT_NUMBER_00, 'H' => '[$EUR ]#,##0.00_-', 'I' => \PHPExcel_Style_NumberFormat::FORMAT_NUMBER_00, )); }); })->download('xlsx');; } 

看来你正在尝试处理太多的进程,同时需要大量的内存,你应该使用Laravel集合的chunk()方法,如下所示:

 Order::orderBy('created_at','desc')->chunk(10, function($orders)use ($sheet) { foreach($orders as $index => $order) { // Do your stuff here... } } 

希望这可以帮助!