请帮助..我只是想显示和组织特定类别
下的类别和每个标准我的控制器中有这段代码
public function readCriteria(Request $req)
{
$dataCategories = Category::all();;
$catCriteria = [];
foreach ($dataCategories as $dataCategory) {
array_push($catCriteria,DB::table('criterias')
->where('cat_id', $dataCategory->id)
->get());
}
return view('admin.criterias', compact('dataCategories')) -> with('catCriteria',collect($catCriteria));
}
在我看来是这个
@foreach($dataCategories as $dataCategory)
<div class="col-lg-3">
<div class="panel-body">
<div class="panel panel-default">
<div class="panel-heading">
{{$dataCategory->cat_name}}
{{$dataCategory->id}}
</div>
<!-- /.panel-heading -->
<div class="panel-body">
@forelse($catCriteria->where('cat_id',$dataCategory->id) as $criteria)
{{ $criteria->cri_name }} : {{ $criteria->cri_points }}
<br>
@empty
<em>No Data</em>
@endforelse
</div>
<!-- /.panel-body -->
</div>
</div>
</div>
@endforeach
答案 0 :(得分:2)
在您的情况下,更好的选择是使用relationships:
添加以下方法:
类别型号:
public function criterias()
{
return $this->hasMany('App\Criteria', 'cat_id');
}
标准模型:
public function category()
{
return $this->belongsTo('App\Category', 'cat_id');
}
通过这种关系,在控制器中你可以这样做:
public function readCriteria(Request $req)
{
$dataCategories = Category::with('criterias')->get();
return view('admin.criterias', compact('dataCategories'));
}
在视图中你所要做的就是:
@foreach($dataCategories as $dataCategory)
<div class="col-lg-3">
<div class="panel-body">
<div class="panel panel-default">
<div class="panel-heading">
{{$dataCategory->cat_name}}
{{$dataCategory->id}}
</div>
<!-- /.panel-heading -->
<div class="panel-body">
@forelse($dataCategory->criterias as $criteria)
{{ $criteria->cri_name }} : {{ $criteria->cri_points }}
<br>
@empty
<em>No Data</em>
@endforelse
</div>
<!-- /.panel-body -->
</div>
</div>
</div>
@endforeach