这不是重复的,而是与主题Query inside for loop in laravel
有关这是laravel中用于将查询放入循环内的正确代码
//controller
public function dtrdata()
{
for($i=1;$i<=$totalnumdays;$i++){
$query= DB::table('dtrrecords')
->where('dtrrecords.bio_id', $i)
}
return view('pages/admin.dtrdata', compact('query','i'));
}
//view
@foreach($query as $row => $rows1)
<tr>
<td>{{$rows1->AM_IN}}</td>
</tr>
@endforeach
答案 0 :(得分:1)
您的循环有几个问题。首先,您将在每次迭代中覆盖$query
变量。其次,您需要调用->get()
来执行查询并返回结果。下面说明了如何将多个查询结果添加到单个集合中,然后在视图中循环结果:
public function dtrdata()
{
$collection = collect();
for($i=1;$i<=$totalnumdays;$i++){
$records = DB::table('dtrrecords')->where('dtrrecords.bio_id', $i)->get();
$collection->concat($records)
}
return view('pages/admin.dtrdata', compact('collection'));
}
@foreach($collection as $item)
<tr>
<td>{{ $item->AM_IN} }</td>
</tr>
@endforeach
答案 1 :(得分:0)
您可以通过另一种解决方案来完成您的工作而无需循环:
public function dtrdata()
{
// Make an array from 1 to $totalnumdays using php range function
// follow the link for range function https://www.w3schools.com/php/func_array_range.asp
$numDays = range(1,$totalnumdays);
$query= DB::table('dtrrecords')
->whereIn('dtrrecords.bio_id', $numDays) // Use laravel whereIn method
->get();
return view('pages/admin.dtrdata', compact('query'));
}
//view
@foreach($query as $row => $rows1)
<tr>
<td>{{$rows1->AM_IN}}</td>
</tr>
@endforeach