gpt4 book ai didi

php - 如何显示数据库中的所有行 - Laravel 5.2?

转载 作者:太空宇宙 更新时间:2023-11-03 10:39:43 24 4
gpt4 key购买 nike

我的 Laravel 应用程序有一个简单的问题。但我找不到任何解决方案。请在此处查看我的代码:

Controller :

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'));
}

Blade View :

<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 .

如果数据库中只有一个那么它可以( see )查看。但是当有更多的时比一个然后它显示在一个 row 与所有数据( see )。我该如何处理这些事情?我认为它应该运行另一个循环,但我该怎么做呢?提前致谢。

最佳答案

因此,如果您使用的是 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>

或者,如果您不想那样做,而不是使用多个查询来获取数据,只需使用一个查询,因为所有字段都在同一个表中,然后,您可以使用上面的示例。

尽情享受吧! :)

关于php - 如何显示数据库中的所有行 - Laravel 5.2?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40627375/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com