2017-07-12 39 views
1

使用this lib上傳的作品很棒。我有一些excel中的對象,我會通過它們來做我想做的事情。Laravel:計數上傳並返回那些

問題是,上傳Excel時,我應該檢查一個特定的對象是否已經存在,如果是這樣,則增加$rejected變量,否則創建並增加$uploaded變量。因此,我想返回結果:有多少上傳,有多少被拒絕?最好的辦法是什麼?很明顯,我不能在函數內部訪問這些變量。這裏最好的做法是什麼?

public function uploadUsingFile($file) 
    { 
     $rejected = 0; 
     $uploaded = 0; 

     Excel::load($file, function ($reader) { 


     foreach ($reader->toArray() as $row) 
     { 

      $plateAlreadyExist = Plate::where('serial_number', $row['plate_serial_number'])->exists(); 

      if ($plateAlreadyExist) { 
       $rejected += 1;continue; 
      } 

      $supplier   = Supplier::firstOrCreate(['name' => $row['supplier_name']]); 
      $statusName  = EquipmentStatusCode::firstOrCreate(['name' => $row['status_name']]); 
      $plateType   = PlateType::firstOrCreate(['name' => $row['plate_type_name']]); 
      $process   = Process::firstOrCreate(['name' => $row['process_name']]); 
      $project   = Project::firstOrCreate(['name' => $row['project_name']]); 
      $plateQuality  = PlateQuality::firstOrCreate(['name' => $row['plate_quality']]); 
      $wafer    = Wafer::firstOrCreate(['serial_number' => $row['wafer_serial_number']]); 

      $data = [ 
       'serial_number'   => $row['plate_serial_number'], 
       'crc_code'     => $row['crc_code'], 
       'supplier_id'    => $supplier['id'], 
       'equipment_status_code_id' => $statusName['id'], 
       'plate_type_id'   => $plateType['id'], 
       'process_id'    => $process['id'], 
       'project_id'    => $project['id'], 
       'plate_quality_id'   => $plateQuality['id'], 
       'wafer_id'     => $wafer['id'], 
       'created_by'    => Auth::user()->id, 
      ]; 

      if($data) 
      { 
       Plate::create($data); 
       $uploaded += 1; 
      } 
      } 


     }); 
return [ 'uploaded' => $uploaded, 'rejected' => $rejected ]; 
    } 

回答

0

您可以通過使用關鍵字use傳遞一個參考變量進入封閉:

... 
Excel::load($file, function ($reader) use(&$rejected, &$uploaded){ 
... 
} 

Anonymous Functions

+0

我已經試過這種方法。由於某種原因,它不工作。 – user3641381

+0

我已經更新了我的答案,您是否使用'&'運算符通過引用傳遞變量? – Yat23

+0

謝謝!這似乎工作。你會不會在你的回答中解釋與這一切有關的'&'? – user3641381