我正在使用Laravel的Q& A应用程序。 在这里,我有两个迁移或数据库表,一个是question_bank,第二个是answer_choices。 问答表之间有一对多的关系。 在检索问题时,我想检索与此问题相关的所有答案。 p>
为此,我写了一个方法: p>
public function getQuestion($ id){
$ question = QuestionBank :: find( $ id);
$ answers = AnswerBank :: where('question_id','=',$ id) - > get();
$ question-> answers = $ answers;
return Response :: json($ question);
}
code> pre>
answer_choices迁移是: p>
class AnswerChoices extends Migration {
公共函数up()
{
Schema :: create('answer_choices',function(Blueprint $ table){
$ table-> increments('id');
$ table-> integer(' question_id') - > unsigned();
$ table-> mediumtext('answer_text');
$ table-> boolean('correct') - > nullable();
$ table-&gt ; foreign('question_id') - >引用('id') - > on('question_bank');
});
}
公共函数down()
\ {
\ drop('answer_choices');
}
}
code> pre>
模型为: p>
&lt ;?php
class AnswerBank扩展\ Eloquent {
protected $ fillable = [];
protecte d $ table =“answer_choices”;
}
code> pre>
问题模型是 p>
<?php \ 问题解决方案扩展\ Eloquent {
protected $ fillable = [];
protected $ table =“question_bank”;
}
code> pre>
我预计我会得到 结果为 question.answers:[{},{},{}] code>
但是在客户端我得到它像“question.answers”:{} code >作为空白对象。 当我只返回 $ answers code>时,它会显示数组中的所有答案对象,如 [{},{},{]] code>。 p>
如何在JavaScript中将答案对象作为对象数组? p>
div>