1

我的模型之间有以下关系:

Assignment hasMany Question
Question belongsTo Assignment
Question hasMany Answer
Answer belongsTo Question

我想要一个可以保存作业、问题和答案的表单。

该表格几乎可以使用,它保存了作业信息和问题,但没有保存答案。

分配控制器创建操作:

function create() {
        if (!empty($this->data)) {

        var_dump($this->data);

        unset($this->Assignment->Question->validate['assignment_id']);
        unset($this->Assignment->Question->Answer->validate['question_id']);
        $this->Assignment->saveAll($this->data, array('validate' => 'first'));
    }
}

创建.ctp

Create new assignment
<?php

echo $this->Form->create('assignment', array('action' => 'create'));
echo $this->Form->input('Assignment.title');
echo $this->Form->input('Assignment.type');
echo $this->Form->input('Question.0.question');
echo $this->Form->input('Question.0.Answer.0.answer');
echo $this->Form->end('Create');

?>
4

2 回答 2

0

我决定独立保存所有内容。

您如何看待这种可能性?

function create() {

    if (!empty($this->data)) {
        if ($this->Assignment->save($this->data)) {
            foreach($this->data['Question'] as $question) {
                $this->Question->create();
                $question['assignment_id'] = $this->Assignment->getLastInsertId();

                if($this->Question->save($question) && $failed == false) {
                    foreach ($question['Answer'] as $answer) {
                        $this->Answer->create();
                        $answer['question_id'] = $this->Question->getLastInsertId();

                        $this->Answer->save($answer);                           
                    }
                }


            }
        }   
    }

}
于 2011-07-30T16:28:34.363 回答
0

也许是因为:

Assignment hasMany Question

但是作业没有答案。

如果您使用正确的递归选项在 Assignment 上找到('all'),它将显示相关模型上的所有条目。但是在创建新分配时,它只会保存直接相关的表。答案不是一个。

为了创建新答案,您可以在作业和答案之间建立关联,或者在保存创建的作业后创建一个函数来创建答案。

你可以在 assignments_controller.php

function create() {
    $this->Assignment->saveAll($this->data, array('validate' => 'first'));
    $this->loadModel('Answer');
    $data[] = array(
        'question_id' => GET_THE_ID_OF_LAST_QUESTION_INSERTED
    );
    $this->Answer->save($data);
}

我不确定,但我认为您可以使用以下方法插入最后一个问题的 id:

$this->Assignment->Question->id;

顺便说一句...为什么要在创建新作业/问题后自动创建新答案?这没有道理。

于 2011-07-30T14:38:42.813 回答