我正在尝试创建一个可以创建和回答测验的应用程序。 创建部分已经完成,我可以保存测试,问题和答案。
他们之间的关系:
Test $hasMany Question
Question $hasMany Answer
我创建了一个viewTest,它使用foreach显示一个选定的Test和它的相关问题:
echo $test['Test']['id'];
echo '</br>';
foreach ($test['Question'] as $question){
echo $question['text'];
echo '<br>';
如何检索与每个问题相关的答案数据?
*编辑*
测试模型关系:
public $hasMany = array('Question' => array('className' => 'Question', 'foreignKey' => 'idTest'));
其中idTest是数据库中的foreignKey
问题模型关系:
public $belongsTo = array('Test' => array('className' => 'Test', 'foreignKey' => 'idTest'));
public $hasMany = array('Answer' => array('className' => 'Answer', 'foreignKey' => 'idQuestion'));
答案模型关系:
public $belongsTo = array('Question' => array('className' => 'Question', 'foreignKey' => 'idQuestion'));
测试返回:
array (size=2)
'Teste' =>
array (size=4)
'id' => string '2' (length=1)
'dataLimite' => string '2014-09-25' (length=10)
'valorTeste' => string '2' (length=1)
'numQuestoes' => string '2' (length=1)
'Questao' =>
array (size=2)
0 =>
array (size=3)
'id' => string '3' (length=1)
'idTeste' => string '2' (length=1)
'descricao' => string 'questao1 ' (length=9)
1 =>
array (size=3)
'id' => string '4' (length=1)
'idTeste' => string '2' (length=1)
'descricao' => string 'dfsdfa' (length=6)
在Test的相同视图中,Question返回:
array (size=3)
'id' => string '3' (length=1)
'idTeste' => string '2' (length=1)
'descricao' => string 'questao1 ' (length=9)
修改
在问题视图中,问题返回:
array (size=3)
'Questao' =>
array (size=3)
'id' => string '3' (length=1)
'idTeste' => string '2' (length=1)
'descricao' => string 'questao1 ' (length=9)
'Teste' =>
array (size=4)
'id' => string '2' (length=1)
'dataLimite' => string '2014-09-25' (length=10)
'valorTeste' => string '2' (length=1)
'numQuestoes' => string '2' (length=1)
'Alternativa' =>
array (size=2)
0 =>
array (size=5)
'id' => string '1' (length=1)
'idQuestao' => string '3' (length=1)
'isRespostaCerta' => boolean false
'respostaUsuario' => null
'descricao' => string 'alternativa 1' (length=13)
1 =>
array (size=5)
'id' => string '2' (length=1)
'idQuestao' => string '3' (length=1)
'isRespostaCerta' => boolean true
'respostaUsuario' => null
'descricao' => string 'alternativa 2' (length=13)
答案 0 :(得分:0)
你有没有在$ question ['Answer']试过foreach()?尝试调试($ question)并查看它是否检索了一系列答案。有时您需要$ hasAndBelongsToMany。
答案 1 :(得分:0)
<强>解决强>
在我的TestsController上,我创建了一个viewTests方法,该方法获取Test.id = $ id(来自索引表)的数据;
$test = $this->Test->findById($id);
然后我在te Session中写了$ id并重新编写了QuestionController
$this->Session->write('idTest',$id);
return $this->redirect(array('controller' => 'questions','action' => 'viewTest'));
在QuestionController上,我创建了另一个从Session $ idTest信息中读取的viewTests。
$idTest = $this->Session->read('idTest');
$this->set('idTest', $idTest);
然后我搜索与测试相关的问题
$this->loadModel('Question');
$questoes = $this->Question->find('all', array(
'conditions' => array('Question.idTest'=>$idTest)
));
$this->set('questions', $questions);
我的tests_view检索答案:
foreach ($questions as $question){
foreach ($question['Answer'] as $answer){
}
}