我有两张桌子。
contenttype返回我的内容类型列表,我用foreach在页面上显示它们。例如救护车服务,血库,诊所等,如快照所示。
同时我从另一个表(内容)中获取每种类型的内容总数。
我成功获得了每种类型的内容总数,并在foreach上显示在刀片上。 但情况是我想显示每种内容类型的内容数量。 像这样 救护车服务8, 血库7, 诊所4。 我的控制器方法是:
public function index()
{
if (Gate::allows('edit-content', auth()->user())) {
// below line returns list of content type e.g Ambulance service
$type = DB::table('contenttype')->distinct('label')->orderBy('label', 'asc')->paginate(10);
//below line counts the number of each content type e.g. Ambulance service 10.
$count = Content::selectRaw('type, count(*)total')->groupBy('type')->get();
return view('admin.content_listing', compact('type', 'count'));
} else {
abort(403, "Unauthorized");
}
}
这是刀片代码:
@foreach ($count as $c)
<span class="label label-danger">{{ $c->total }} </span>
@endforeach
@foreach ($type as $t)
<div class="list-group-item">
<a href="{{ route('content.type.listing', $t->type ) }}" > {{ $t->label }}
<span class=" pull-right glyphicon glyphicon-search"></span></a>
<a href="{{ route('content.add.form') }}" class="pull-right "><span class="col-md-1 glyphicon glyphicon-plus-sign"></span></a>
</div>
@endforeach
输出为:
如果我将循环放在第二个循环中,那么它当然会变成我不想要的嵌套循环。
我需要展示救护车8, 美容诊所8, 血库1, 等
如果有人知道解决方案,请分享它! 我尝试了不同的方法但没有成功。
答案 0 :(得分:1)
您是否尝试在单个查询中执行联接,而不是创建两个查询并尝试将其结果合并到视图中?对列名进行某些假设并将分页放在一边,实际的SQL将类似于:
SELECT contenttype.*, count(content.id) FROM contenttype LEFT JOIN content ON contenttype.id = content.type GROUP BY contenttype.label ORDER BY contenttype.label ASC;
使用Laravel的查询构建器功能实现此查询所需的代码在documentation中有详细记录。