【问题标题】:Laravel custom query for answer and question databaseLaravel 自定义查询答案和问题数据库
【发布时间】:2020-11-15 05:23:08
【问题描述】:

我有三个表,分别称为考试、问题和答案。它们通过外国身份证连接。我有加入问答表的功能。我有 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'));
}

【问题讨论】:

    标签: mysql laravel laravel-5 query-builder


    【解决方案1】:

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

    你的关系应该是这样的:

    考试模式:

    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();
    

    这应该为您提供一系列问题以及相关答案。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-09
      • 1970-01-01
      • 2021-03-01
      • 1970-01-01
      • 2022-01-11
      • 1970-01-01
      • 2023-03-14
      • 1970-01-01
      相关资源
      最近更新 更多