2017-04-06 31 views
0

在我的應用程序中,我有一個模型可以捕獲訂單上的各個訂單項。可以有無數個。它們通過外鍵(msr_id)綁定到「父」模型。CakePHP:將數據保存在foreach循環中

有時,用戶需要複製訂單,以便項目可以重新排序。我無法將各個訂單項複製到新記錄。這是在我的控制器檢索的行項目代碼:

/*Get the MSR line items and build an array out of them. The 
line items are tied to the main record by $orig['Msr']['id']*/ 
$this->loadModel('MsrLineItem'); 
$lines = $this->MsrLineItem->find('all', array('conditions'=>array('msr_id'=>$orig['Msr']['id'], 'MsrLineItem.deleted_record'=>0))); 

當調試$線,它顯示了訂單,我試圖複製上存在的兩個行項目。這是在同一個控制器,我試圖用爲訂單項數據複製到新的記錄代碼:

//Save the non-line item data first 
if($newmsr = $this->Msr->save($new)) { 
    //Set the line item ID to the new record ID (from $newmsr) 
    $this->MsrLineItem->set('msr_id', $newmsr['Msr']['id']); 
    //Loop through the line items, saving each one to the new record 
    foreach($lines as $line) { 
    $newli['MsrLineItem']['quantity'] = $line['MsrLineItem']['quantity']; 
    $newli['MsrLineItem']['unit_of_meas'] = $line['MsrLineItem']['unit_of_meas']; 
    $newli['MsrLineItem']['description'] = $line['MsrLineItem']['description']; 
    $newli['MsrLineItem']['part_no'] = $line['MsrLineItem']['part_no']; 
    $newli['MsrLineItem']['unit_price'] = $line['MsrLineItem']['unit_price']; 
    $this->MsrLineItem->save($newli, 'msr_id'); 
    } 
    $this->Session->setFlash(__('The MSR has been copied successfully.')); 
    $this->redirect(array('action' => 'edit', $newmsr['Msr']['id'])); 

我的問題是,我只捕獲循環的最後一個項目。之前發生的任何情況都會被忽略。如何捕獲所有訂單項?

回答

0

我想通了。我要叫$這個 - > MsrLineItem->創建()在每次循環的開頭:

foreach($lines as $line) { 
    $this->MsrLineItem->create(); 
    //Copy the line items 
} 

補充說,行至環,它的工作現在。