查询问题并列出它们及其答案选项在 Laravel 5.3 中不起作用

Querying questions and listing them with its answer options not working in Laravel 5.3

我正在 Laravel 5 开发一个多项选择测验应用程序。3.I 有三个 table:

questions table
id ->pk
question
is_active

answers table
id ->pk
question_id - fk references questions@id
answer

correct_answer table
id ->pk
answer_id ->references answers@id

现在我想select每个问题都来自问题table 以及答案 table 中的相应答案。这就是我想要列出结果的方式:

question one
answer 1
answer 2
answer 3
answer 4

question two
answer 1
answer 2
answer 3
answer 4

我试过这个:

 $questions = DB::table("questions")  
                    ->select("question")  
                   ->join("answers","answers.question_id",
                        "=","questions.id")
                        ->where("questions.is_active",1)
                        ->groupBy("questions.question")
                        ->get();

但是这个查询给了我以下结果:

question one
answer 1
question two
answer 1

当每个问题的答案中有 4 个选项时,只返回每个问题的第一个选项 table

id  question_id answer
1   2           answer 1
2   2           answer 2
3   2           answer 3
4   2           answer 4
5   3           answer 1
6   3           answer 2
7   3           answer 3
8   3           answer 4

我也试过这个但得到了相同的结果:

$questions = DB::table('questions')
        ->leftjoin('questions','question_id',
            'answers.question_id','=','questions.id')
        ->select('*')                    
        ->where('questions.is_active','=',1)
        ->groupBy('question')       
        ->get();

问题模型有许多答案模型。我已经在模型中设置了这个。请帮我解决这个问题。我做错了什么?

我建议使用 Eloquent ORM 而不是使用查询生成器。

我不确定您是否在模型中设置了正确的关系。

那么让我们从头开始吧。

每个问题都有多个答案。所以关系将是一对多

问题模型

class question extends Model
{
    /**
     * Get the answers of a question
     */
    public function answers()
    {
        return $this->hasMany('App\Answer');
    }
}

答案模型(如果您想获得答案的问题,请打开 - 否则请忽略)

class Answer extends Model
{
    /**
     * Get the question of an answer
     */
    public function question()
    {
        return $this->belongsTo('App\Question');
    }
}

在控制器动作中

$questions = Question::with('answers')->get();

希望这会有所帮助。