dpfps86064 2014-05-26 11:14
浏览 106
已采纳

将一个对象数组分配给Laravel中的另一个对象的键

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?

  • 写回答

3条回答 默认 最新

  • douyuefu1372 2014-05-31 12:16
    关注

    Answer Given by Creator is totally fine just having a small mistake. Corect that and your code will be run.
    Change this function

    public function answers(){
    
        return $this->HasMany('AnswerBank','id','question_id');
    
     }
    

    to

    public function answers(){
    
        return $this->HasMany('AnswerBank','question_id','id');
    
    }
    

    Replace question_id with id and it will work.
    And return question object with answers like this

    public function getQuestion($id){  
        $answers=QuestionBank::with('answers')->find($id);
        return Response::json($answers);
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100
  • ¥15 关于#hadoop#的问题
  • ¥15 (标签-Python|关键词-socket)
  • ¥15 keil里为什么main.c定义的函数在it.c调用不了