HasMany通过多个条目 - 新的

时间:2014-03-26 12:29:10

标签: cakephp associations has-many-through has-many

我正在通过CakePHP食谱中的示例来使用CourseMembership HasMany,但我无法弄清楚如何同时在CourseMembership(即student_id和成绩)中添加新课程和多个条目。

课程有很多课程 学生有很多课程成绩 课程成员属于学生,课程

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

数据阵列成功保存,插入新课程正常,但只插入1个没有student_id或成绩的CourseFmbership条目。

数据数组如下所示:

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'
    )
)

2 个答案:

答案 0 :(得分:0)

从表格输入中删除课程成员---使用此

    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');

答案 1 :(得分:0)

知道了!我使用了推荐的课程控制器,并使用以下课程/添加视图,它现在可以使用了。感谢

    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');