I tried nested foreach few times. but i failed. How to foreach data choices. in duplicates foreach.
Controller
$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
but it cant read that $choice
最佳答案
从聊天讨论来看,Question
模型和Choice
模型与Topic
模型有关系
您需要像这样定义关系
Topic Model
public function choices(){
return $this->hasMany('App\Choice');
}
public function questions(){
return $this->hasMany('App\Question');
}
Question Model
public function topic(){
return $this->belongsTo('App\Topic');
}
Choice Model
public function topic(){
return $this->belongsTo('App\Topic');
}
Now Fetch data
$duplicates = Question::selectRaw("count('id') as total, topic_id")->with('topic', 'topic.choices')->groupBy('topic_id')->get();
Template Render
@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
关于laravel - 2 模型 2 foreach 在 1 个 View 中。拉维尔,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50940253/