mysql - 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'));
}
解决方案
如果你正确地建立了关系,你就不需要加入来实现这一点。
你的关系应该是这样的:
考试型号:
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();
这应该为您提供一系列带有相关答案的问题。
推荐阅读
- c++ - 提升属性树以解析自定义配置格式
- javascript - 在 Flow 中声明非箭头函数
- python - 在 Numpy Python 中将一维数组附加到多维数组
- jquery - dd/mm/yyyy 中的 bootstrap-datepicker - 设置 minDate 或 maxDate 后,所选日期显示为 mm/dd/yyyy
- firebase - 生成唯一组码
- javascript - 在 Windows 上打包 Electron/React 应用程序时出现 Webpack 错误
- autohotkey - 如何在两个 chrome 窗口之间复制我的输入和单击操作?
- javascript - JS 将 forEach 变量传递给查找函数
- php - 如何使用 MySQL 数据库中的选定值创建 HTML 选择?
- r - 将值传递给 Zelig