我的Laravel应用程序有一个简单的问题。但我找不到任何解决方案。请在此处查看我的代码:
控制器:
public function index(){
$members = Member::paginate(15);
$meal_entry = Member::all();
$breakfast = DB::SELECT("SELECT self_meal_breakfast + guest_meal_breakfast AS breakfast FROM meal_entry");
$lunch = DB::SELECT("SELECT self_meal_lunch + guest_meal_lunch AS lunch FROM meal_entry");
$dinner = DB::SELECT("SELECT self_meal_dinner + guest_meal_dinner AS dinner FROM meal_entry");
$total_meal = DB::SELECT("SELECT self_meal_breakfast + self_meal_lunch + self_meal_dinner + guest_meal_breakfast + guest_meal_lunch + guest_meal_dinner AS total FROM meal_entry");
return view('member.mealView', compact('members','data','breakfast','lunch','dinner','meal_entry','total_meal'));
}
刀片视图
<tbody>
<tr>
@foreach($meal_entry as $value)
<td>{{ $value->created_at }}</td>
@endforeach
@foreach($breakfast as $value)
<td>{{ $value->breakfast }}</td>
@endforeach
@foreach($lunch as $value)
<td>{{ $value->lunch }}</td>
@endforeach
@foreach($dinner as $value)
<td>{{ $value->dinner }}</td>
@endforeach
@foreach($total_meal as $value)
<td>{{ $value->total }}</td>
@endforeach
@foreach($meal_entry as $value)
<td>{{ $value->created_at }}</td>
@endforeach
</tr>
</tbody>
表格: meal_entry 。
如果数据库中有一个row
,那么可以查看它( see )。但是当row
多于一个时,在一个row
中显示所有数据( see )。我该如何处理这些事情?我认为它应该运行另一个循环,但我怎么能这样做?提前谢谢。
答案 0 :(得分:4)
所以,如果你正在使用Laravel,那么最好的功能之一是访问者:
https://laravel.com/docs/5.2/eloquent-mutators#accessors-and-mutators
您可以创建新属性并将其用作模型属性。
对于某些东西非常有用。
class Meal extends Model
{
public function getTotalBreakfastAttribute()
{
return $this->self_meal_breakfast + $this->guest_meal_breakfast;
}
}
然后,将此访问器用作属性:
<tbody>
@foreach($foods as $value)
<tr>
<td> {{$value->total_breakfast}} </td>
<td> {{$value->created_at}} </td>
</tr>
@endforeach
</tbody>
或者如果您不想这样做,而不是使用多个查询来获取数据,只需使用一个,因为所有字段都在同一个表中,然后,您可以使用上面的示例。 / p>
享受! :)
答案 1 :(得分:0)
一个快速补丁是只做一个查询,然后对视图进行计算(我知道在视图中进行计算不是一个好习惯,但这是我能看到的最简单的方法)。 / p>
就像这样:
<强>控制器:强>
public function index(){
$members = Member::paginate(15);
return view('member.mealView', compact('members'));
}
刀片视图
<tbody>
@foreach($members as $meal_entry)
<tr>
<td>{{ $meal_entry->created_at }}</td>
<td>{{ $breakfast = $meal_entry->self_meal_breakfast + $meal_entry->guest_meal_breakfast }}</td>
<td>{{ $lunch = $meal_entry->self_meal_lunch+ $meal_entry->guest_meal_lunch}}</td>
<td>{{ $dinner = $meal_entry->self_meal_dinner + $meal_entry->guest_meal_dinner }}</td>
<td>{{ $breakfast + $lunch + $dinner }}</td>
<td>{{ $meal_entry->created_at }}</td>
</tr>
@endforeach
</tbody>
请记得添加
{{ $members->links() }}
你想要的分页链接。