habtm 上的 saveall 创建重复的新行

saveall on habtm creates duplicate new rows

我有一个带有 lessons/Students table 的简单 HABTM。我只是通过一个 while 循环与现有学生一起创建一个新课程,所以我应该得到 2 个新行。我正在测试这个功能。我得到的是课程 table 中的 4 行新行,而不是 2 行。我不知道为什么会创建额外的 2 行,因为它们是调试中输出的 2 行新行的副本。一切都像加入 lesson/student table 中的条目一样正确保存并且所有 FK 都存在。

只是为了增加混乱,有时相同的代码会产生所需的 2 行。这是 unstable 所以我做错了什么。我按照保存手册中的 habtm 阵列设置进行操作。

http://book.cakephp.org/2.0/en/models/saving-your-data.html

 private function book_lessons($lesson=null) {

       // debug( $lesson);

     $i=0;
     while ($i<2)
     {
      $date=date('Y-m-d');
      $data[$i]=array();
      $this->Lesson->create();

      $data[$i]['Lesson']['lesson_date']= $date;
      $data[$i]['Lesson']['start_time']= $lesson['Lesson']['start_time'];
      $data[$i]['Lesson']['end_time']=$lesson['Lesson']['end_time'];

      $data[$i]['Lesson']['schedule_rec']= 1;
      $data[$i]['Lesson']['subject_id']= $lesson['Lesson']['subject_id'];
      $data[$i]['Lesson']['tutoring_type_id']= 1;
      $data[$i]['Lesson']['tutor_id']= $lesson['Lesson']['tutor_id'];
      $data[$i]['Lesson']['subject_id']= $lesson['Lesson']['subject_id'];
      $data[$i]['Lesson']['term_id']= $lesson['Lesson']['term_id'];

      $data[$i]['Student']['id']=$lesson['Student']['id'];

     $i=$i+1;

     }


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

public $hasAndBelongsToMany = array(

        'Student' => array(
            'className' => 'Student',
            'joinTable' => 'lessons_students',
            'foreignKey' => 'lesson_id',
            'associationForeignKey' => 'student_id',
            'unique' => 'keepExisting',

        )
    );


array(
    (int) 0 => array(
        'Lesson' => array(
            'lesson_date' => '2015-06-11',
            'start_time' => '16:00:00',
            'end_time' => '17:00:00',
            'schedule_rec' => (int) 1,
            'subject_id' => '16',
            'tutoring_type_id' => (int) 1,
            'tutor_id' => '12',
            'term_id' => '10'
        ),
        'Student' => array(
            'id' => '206'
        )
    ),
    (int) 1 => array(
        'Lesson' => array(
            'lesson_date' => '2015-06-11',
            'start_time' => '16:00:00',
            'end_time' => '17:00:00',
            'schedule_rec' => (int) 1,
            'subject_id' => '16',
            'tutoring_type_id' => (int) 1,
            'tutor_id' => '12',
            'term_id' => '10'
        ),
        'Student' => array(
            'id' => '206'
        )
    )
)

移动 $this->Lesson->create();跳出循环。当你只有 create() 方法时,Cake 仍然会保存多条记录。