我的模型之间有以下关系:
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'));
}
}
create.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');
?>
答案 0 :(得分: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;
顺便说一下......为什么要在创建新的作业/问题后自动创建新的答案?这毫无意义。
答案 1 :(得分: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);
}
}
}
}
}
}