I am working on a Q&A app in Laravel. Here, I have two migrations or database tables, one is question_bank and second is answer_choices. There is one to many relation between question and answers table. While retrieving a question, I want to retrieve all of the answers which are related with this question.
For this i wrote a method:
public function getQuestion($id){
$question=QuestionBank::find($id);
$answers=AnswerBank::where('question_id','=',$id)->get();
$question->answers=$answers;
return Response::json($question);
}
The answer_choices migration is :
class AnswerChoices extends Migration {
public function 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->foreign('question_id')->references('id')->on('question_bank');
});
}
public function down()
{
Schema::drop('answer_choices');
}
}
And the model is :
<?php
class AnswerBank extends \Eloquent {
protected $fillable = [];
protected $table = "answer_choices";
}
Question model is
<?php
class QuestionBank extends \Eloquent {
protected $fillable = [];
protected $table = "question_bank";
}
I expected i will get result as question.answers:[{},{},{}]
but on client side I am getting it like "question.answers":{}
as a blank object. When I return only $answers
, it shows all the answer objects in the array like [{},{},{]]
.
How can I get the answers objects as an array of objects in JavaScript?