HasMany Through multiple entries
I am playing around with the CourseMembership HasMany through example in the CakePHP cookbook but I cant figure out how to add a new Course and multiple entries into CourseMembership (ie student_id and grade) all at the same time.
Course hasMany Coursemmembership
Student hasMany Coursemeembership
Coursemembership belongsTo Student, Course
//CoursemmembershipsController
public function add() {
if ($this->request->is('post')) {
$this->Coursemembership->create();
if ($this->Coursemembership->saveAll($this->request->data,array('deep' => true))) {
$this->Session->setFlash(__('The coursemembership has been saved.'));
//return $this->redirect(array('action' => 'index'));
} else {
$this->Session->setFlash(__('The coursemembership could not be saved. Please, try again.'));
}
debug($this->request->data);
}
$courses = $this->Coursemembership->Course->find('list');
$students = $this->Coursemembership->Student->find('list');
$this->set(compact('courses', 'students'));
}
__
//Coursemembership/view/add
$this->Form->create('Coursemembership');
echo $this->Form->input('Course.name');
echo $this->Form->input('0.Coursemembership.student_id');
echo $this->Form->input('0.Coursemembership.grade');
echo $this->Form->input('1.Coursemembership.student_id');
echo $this->Form->input('1.Coursemembership.grade');
?>
The data array successfully saves, inserts a new Course fine, but inserts only 1 Coursemembership entry with no student_id or grade.
Data array looks like:
array(
'Course' => array(
'name' => 'Math 101'
),
(int) 0 => array(
'Coursemembership' => array(
'student_id' => '1',
'grade' => '5'
)
),
(int) 1 => array(
'Coursemembership' => array(
'student_id' => '2',
'grade' => '2'
)
)
)
从表单输入中删除Coursemembership ---使用此
echo $this->Form->create('Coursemembership');
echo $this->Form->input('Course.name');
echo $this->Form->input('0.student_id');
echo $this->Form->input('0.grade');
echo $this->Form->input('1.student_id');
echo $this->Form->input('1.grade');
echo $this->Form->end('save');
Got it! I used the Course controller as recommended, with the following Course/add view and it now works. Thanks
echo $this->Form->input('Course.name');
echo $this->Form->input('Coursemembership.0.student_id');
echo $this->Form->input('Coursemembership.0.grade');
echo $this->Form->input('Coursemembership.1.student_id');
echo $this->Form->input('Coursemembership.1.grade');
链接地址: http://www.djcxy.com/p/64890.html
上一篇: CakePHP关联不能使用userdata和userdatatype
下一篇: HasMany通过多个条目