我有一个简单的HABTM课程/学生表。我只是通过while循环创建一个现有学生的新课程,所以我应该得到2个新行。我正在测试这个功能。我得到的是课程表中的4个新行而不是2.我不知道为什么要创建额外的2行,因为它们是在调试中输出的2个新行的副本。一切都正确保存,就像加入课程/学生表中的条目一样,并且所有FK都存在。
只是为了增加混淆,有时相同的代码会生成所需的2行。这是不稳定的,所以我做错了。我按照手册中的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'
)
)
)
答案 0 :(得分:0)
移动$ this-&gt; Lesson-&gt; create();跳出循环。只有在create()方法中时,Cake仍会保存多条记录。