CakePHP: Saving data in a foreach loop

时间:2017-04-06 17:19:10

标签: php cakephp

In my application, I have a model that captures individual line items on an order form. There can be an infinite number of them. They are tied to a "parent" model by a foreign key (msr_id).

Sometimes, the user will want to copy the order form so that the items can be reordered. I'm having trouble copying the individual line items to a new record. Here is the code in my controller that retrieves the line items:

/*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)));

When I debug $lines, it shows the two line items that exist on the order form I'm trying to copy. Here is the code in the same controller that I'm trying to use to copy the line item data to the new record:

//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']));

My problem is that I'm only capturing the last line item in the loop. Any that come before that are ignored. How can I capture all of the line items?

1 个答案:

答案 0 :(得分:0)

我明白了。我必须在循环的每次迭代开始时调用$ this-> MsrLineItem-> create():

filename = fullfile('/Users/Tim/Documents/2-Grad-School/Research/Technical-Paper/Latex/Figures/', 'Ult_Stress_vs_Temp');

print(filename, '-dpng')

将该行添加到循环中并且它现在正在工作。