首页 > 解决方案 > Laravel 自定义查询答案和问题数据库

问题描述

我有三个表,称为考试,问题和答案。它们通过外国身份证连接。我有加入问答表的功能。我有 1 个问题和多个答案。当我加入时,我看到许多相同的问题有 1 个答案(这是正常的)。有什么方法可以通过查询生成器在一个查询(数组)中加入 1 个问题和多个答案

考试表

        $table->id();

        $table->string('language_code');
        $table->string('title');
        $table->integer('subcategory_id')->nullable();
        $table->string('section');
        $table->string('class');
        $table->string('subject')->nullable();
        $table->string('time')->default('60');

        $table->timestamps();

问题表

        $table->id();

        $table->integer('exam_id');
        $table->string('q_pic')->nullable();
        $table->string('q_name')->nullable();
        $table->string('q_text');

        $table->timestamps();

答案表

        $table->id();

        $table->integer('user_id');
        $table->integer('question_id');
        $table->text('user_answer')->nullable();
        $table->integer('user_answer_id');
        $table->integer('c_answer_id'); 

        $table->timestamps();

这是我的视图功能

public function view($id)
{
    $questions = DB::table('questions')
        ->leftJoin('answers','answers.question_id','=','questions.id')
        ->where('questions.exam_id','=',$id)
        ->get();

    return view('main/view',compact('questions'));
}

标签: mysqllaravellaravel-5query-builder

解决方案


如果你正确地建立了关系,你就不需要加入来实现这一点。

你的关系应该是这样的:

考试型号:

public function questions()
{
  return $this->hasMany(Question::class);
}

问题模型:

public function exam()
{
  return $this->belongsTo(Exam::class);
}

public function answers()
{
  return $this->hasMany(Answer::class);
}

答案型号:

public function question()
{
  return $this->belongsTo(Question::class);
}

现在您可以像这样查询:

//use App\Question;
$questionsWithAnswers = Question::where('id', $id)->with('answers')->get();

这应该为您提供一系列带有相关答案的问题。


推荐阅读