我想展示一个包含问题和答案的测试。一个问题有4个答案。但我只得到了所有问题的 4 个答案。我该如何解决它?
public function xem($id){
$quests_of_test = QuestofTest::where('id_test', $id)->get();
$ids = $quests_of_test->pluck('id_quest')->all();
$questions = Question::whereIn('id', $ids)->get();
foreach($questions as $quest){
$answers = Answer::where('id_quest', $quest->id)->get();
}
return view('Test::xem', compact('questions', 'answers'));
}
就这样做吧
public function xem($id){
$quests_of_test_ids = QuestofTest::where('id_test', $id)->pluck('id_quest')->toArray();
$questions = Question::query()->whereIn('id', $quests_of_test_ids)->with('answers')->get();
return view('Test::xem', compact('questions'));
}
在视图中,当你迭代$question时,你可以做$question->answer
但在此之前你应该这样做
public function answer()
{
return $this->hasOne(Answer::class, 'id_which_by_related')
//return $this->hasMany(Answer::class, 'id_which_by_related') in case it has many answers so u should foreach it to iterate collection of answers
}
因为 foreach 中的变量被下一次迭代覆盖,所以你得到了上一次迭代数据
处理你的代码,不要再这样做了,请了解连接和关系
原因是变量
$answers
将为foreach内的每个循环重新分配。
您可以使用
$answers = [];
foreach($questions as $quest){
$answers = array_merge($answers, Answer::where('id_quest', $quest->id)->get());
}
如果您正确定义了您的关系,您可以使用 Eager Loading 来获取问题的所有答案。
public function xem($id) {
$quests_of_test = QuestofTest::where('id_test', $id)->get();
$ids = $quests_of_test->pluck('id_quest')->all();
$questions = Question::with('answers')->whereIn('id', $ids)->get();
return view('Test::xem', compact('questions'));
}