2013-08-05 14 views
0

我正在爲我的客戶進行導入,並且這是以100作爲測試的循環工作。在每個循環中,我都可以保存該客戶的數組,但是我認爲將來自每個循環的數組結合起來更快,並在達到100時將它們全部保存在最後。數據來自csv文件。在一個循環中組合數組cakephp

第一件事我想知道什麼是更好的,一次性保存每個循環或一次完成?

我創建的ARRY情況如下:

//Process file 
     if (($handle = fopen('uploads/temp/'.$file, "r")) !== FALSE) 
     while ( (($dop_ar = fgetcsv($handle, 10000, ";")) !== FALSE) && (($_POST['start_id']+1)*100 >= $counter)) { 

      if ($_POST['start_id']*100 <= $counter) { 

       $data_customer = array(
         "Customer" => array (
          "id" => $dop_ar[0], 
          "factuurvoornaam" => $dop_ar[12], 
          "factuurachternaam" => $dop_ar[14] 
          ), 
       ); 

       $this->Customer->create(); 
       if ($this->Customer->save($data_customer)) { 
       // handle the success. 
       //echo 'ok'; 
       } 

      } 

      $counter++; 
     } 

的問題是,我不知道如何將數組,而我在組合循環,這樣我可以在使用白水達到100時的循環結束。如果我是對的,我必須使用索引,以便cakephp知道他必須插入多個客戶。

希望有人能幫助我在這個方向上取得正確的方向。

回答

0

要一次保存多條記錄,只需將它們作爲模型別名的數字元素添加到模型數據數組中即可。所以,你的數據會看起來像:

$dataToSave = array(
    'Customer' => array(
     array(
      'id' => 54, 
      'factuurvoornaam' => 'Test', 
      'factuurachternaam' => '1' 
     ), 
     array(
      'id' => 456, 
      'factuurvoornaam' => 'Test', 
      'factuurachternaam' => '2' 
     ), 
     array(
      'id' => 92, 
      'factuurvoornaam' => 'Test', 
      'factuurachternaam' => '3' 
     ) 
    ) 
); 

試試這個:

$customers = array(); 

if ($handle = fopen('uploads/temp/' . $file, 'r')) { 

    while ($dop_ar = fgetcsv($handle, 10000, ';')) && (($_POST['start_id'] + 1) * 100 >= $counter)) { 

     if ($_POST['start_id'] * 100 <= $counter) { 

      $customers['Customer'][] = array(
       'id' => $dop_ar[0], 
       'factuurvoornaam' => $dop_ar[12], 
       'factuurachternaam' => $dop_ar[14] 
      ); 
     } 
     $counter++; 
    } 
} 

if (!empty($customers)) { 
    $this->Customer->saveAll($customers); 
} 
+0

BadHorsie這正與一個小的變化。我必須改變以下內容:$ customers ['Customer'] [] to $ customers []否則cakephp只做了一次回滾,不知道爲什麼。當插入cakephp檢查每個ID與計數,這會減慢進度。我使用$ this-> Customer-> begin();和$ this-> Customer-> commit();現在,但這不是一個很大的加速。你有什麼建議可以提高插入數據的速度嗎? –

+0

對不起,我沒有測試只是寫了它。我不知道該爲速度提出什麼建議,我想這只是在循環中執行如此多的插入操作的問題。 – BadHorsie