Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/264.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
CakePHP:在foreach循环中保存数据_Php_Cakephp - Fatal编程技术网

CakePHP:在foreach循环中保存数据

CakePHP:在foreach循环中保存数据,php,cakephp,Php,Cakephp,在我的应用程序中,我有一个模型可以捕获订单上的单个行项目。它们的数量可以是无限的。它们通过外键(msr_id)绑定到“父”模型 有时,用户会希望复制订单,以便对项目进行重新排序。我无法将单个行项目复制到新记录。以下是我的控制器中检索行项目的代码: /*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']*/ $t

在我的应用程序中,我有一个模型可以捕获订单上的单个行项目。它们的数量可以是无限的。它们通过外键(msr_id)绑定到“父”模型

有时,用户会希望复制订单,以便对项目进行重新排序。我无法将单个行项目复制到新记录。以下是我的控制器中检索行项目的代码:

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

我的问题是,我只捕获循环中的最后一行项目。在此之前出现的任何问题都将被忽略。如何捕获所有行项目?

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

foreach($lines as $line) {
   $this->MsrLineItem->create();
   //Copy the line items
}
将该行添加到循环中,它现在正在工作