我尝试了嵌套foreach几次。但是我失败了。如何预测数据选择。重复一遍foreach。
控制器
$choices = Choice::where('user_id','=',Auth::id())->get();
$duplicates = Question::selectRaw("count('id') as total, topic_id")->groupBy('topic_id')->get();
return view('choices.index',compact('too','choices','duplicates'));
查看
@foreach ($duplicates as $duplicate)
<tr>
<td style="text-align: center;">{{ $duplicate->topic->id }}</td>
<td style="text-align: center;">@foreach ($choices as $choice) {{ $choice->question_number }} @endforeach</td>
</tr>
@endforeach
我希望结果像
@foreach ($duplicates as $duplicate)
<tr>
<td style="text-align: center;">{{ $duplicate->topic->id }}</td>
<td style="text-align: center;">$choice->question_number }}</td>
</tr>
@endforeach
但无法读取$ choice
答案 0 :(得分:2)
在聊天讨论中,似乎Question
模型和Choice
模型与Topic
模型有关系
您需要定义这样的关系
主题模型
public function choices(){
return $this->hasMany('App\Choice');
}
public function questions(){
return $this->hasMany('App\Question');
}
问题模型
public function topic(){
return $this->belongsTo('App\Topic');
}
选择模型
public function topic(){
return $this->belongsTo('App\Topic');
}
现在获取数据
$duplicates = Question::selectRaw("count('id') as total, topic_id")->with('topic', 'topic.choices')->groupBy('topic_id')->get();
模板渲染
@foreach ($duplicates as $duplicate)
<tr>
<td style="text-align: center;">{{ $duplicate->topic->id }}</td>
<td style="text-align: center;">
@foreach ($duplicate->topic->choices as $choice)
{{ $choice->question_number }}
@endforeach
</td>
</tr>
@endforeach