停止在' saveAll'上获取重复的行在CakePHP中

时间:2015-10-01 13:26:15

标签: php cakephp

在CakePHP中,当我使用以下代码保存数据时,我得到的数据按预期保存,但我将所有数据保存了2次。 $lesson数据变量不检索2个数据副本,因此保存功能是问题所在。我尝试在循环中使用save,这也给出了同样的问题。必须有一些简单的我做错了。

http://book.cakephp.org/2.0/en/models/saving-your-data.html#model-save-array-data-null-boolean-validate-true-array-fieldlist-array

$data=array();
$i=0;

$this->Lessondata->cacheQueries = false;
$this->Lessondata->create( );

foreach ($lessons as $item):
    //  $this->Lessondata->cacheQueries = false; 

    $data[$i]['Lessondata']['lesson_id']=$item['Lesson']['id'];
    $data[$i]['Lessondata']['st_id']=$item['Student']['id'];
    $data[$i]['Lessondata']['tutor_id']=$item['Tutor']['id'];
    $data[$i]['Lessondata']['student_name']=$item['Student']['first_name'].' '.$item['Student']['last_name'];
    $data[$i]['Lessondata']['subject']=$item['Subject']['name'];
    $data[$i]['Lessondata']['tutor_name']=$item['Tutor']['first_name'].' '.$item['Tutor']['last_name'];
    $data[$i]['Lessondata']['class_year']=$item['Student']['class_year'];
    //  debug($data[$i]);
    debug($i);
    $i=$i+1;

endforeach;

$this->Lessondata->saveAll($data);

2 个答案:

答案 0 :(得分:0)

试试吧。

$data = array();
    foreach ($lessons as $item):
        $data['Lessondata'][] = array(
            'lesson_id' => $item['Lesson']['id'],
            'st_id' => $item['Student']['id'],
            'tutor_id' => $item['Tutor']['id'],
            'student_name' => $item['Student']['first_name'] . ' ' . $item['Student']['last_name'],
            'subject' => $item['Subject']['name'],
            'tutor_name' => $item['Tutor']['first_name'] . ' ' . $item['Tutor']['last_name'],
            'class_year' => $item['Student']['class_year'],
        );

    endforeach;

    $this->Lessondata->create();
    $this->Lessondata->saveAll($data);

答案 1 :(得分:0)

这有效但我需要检查重复何时开始。这是一个糟糕的答案,因为我允许一个怪癖。到目前为止还没有其他答案。如果有人提供了合适的答案,我很乐意接受这一点。

$this->Lessondata->create();

foreach ($lessons as $item):
  $ff = $this->Lessondata->find('first', array(
    'conditions' => array('Lessondata.lesson_id' => $item['Lesson']['id'])
  ));

  if (!empty($ff)) {
    debug($item);
    break;
  }

  $data[$i]['Lessondata']['lesson_id'] = $item['Lesson']['id'];
  $data[$i]['Lessondata']['st_id'] = $item['Student']['id'];
  $data[$i]['Lessondata']['tutor_id'] = $item['Tutor']['id'];
  $data[$i]['Lessondata']['student_name'] = $item['Student']['first_name'].' '.$item['Student']['last_name'];
  $data[$i]['Lessondata']['subject'] = $item['Subject']['name'];
  $data[$i]['Lessondata']['tutor_name'] = $item['Tutor']['first_name'].' '.$item['Tutor']['last_name'];
  $data[$i]['Lessondata']['class_year'] = $item['Student']['class_year'];    
  $i = $i+1;
endforeach;
debug($data);

$this->Lessondata->saveAll($data);