如何计算表列值并在刀片文件laravel 5.6中打印 [英] How to count table column values and print in blade file laravel 5.6
问题描述
我正在使用laravel 5.6
,并且我有名为vehicles
的表,其中的列为categoryname
:
I am working with laravel 5.6
and I have table named vehicles
with columns categoryname
:
id number categoryname
1 123 Car
2 589 Van
3 589 Car
4 563 SUV
5 563 Van
现在我在welcome.blade.php
中具有以下blade
视图:
Now I have following blade
view in welcome.blade.php
:
<img src="{{URL::asset('/images/car.png')}}" alt="profile Pic" height="50" width="50" class="center-block">
<div>Car</div>
<div>text text text texttext texttext texttext text trtrttr rrttrtr rrtrttr rtrtrttrtr rtrttrtr rrtrttr rrtrtr</div>
</div>
<div class="col-md-3 text-center">
<img src="{{URL::asset('/images/van.png')}}" alt="profile Pic" height="50" width="50" class="center-block">
<div>Van</div>
<div>text text text texttext texttext texttext text trtrttr rrttrtr rrtrttr rtrtrttrtr rtrttrtr rrtrttr rrtrtr</div>
</div>
我的问题是,现在我需要在categoryname
列中计数相同的值,并在welcome.blade.php
中以这种方式打印它们.
My problem is now I need count same values in categoryname
column and print them like this way in welcome.blade.php
.
<div>Car</div>
<div>2</div>
<div>Van</div>
<div>3</div>
etc...
我有以下控制器来计算列值:
I have following controller to count column values:
$names = Vehicle::groupBy('categoryname')->select('id', 'categoryname', \DB::raw('COUNT(*) as cnt'))->get();
它正在运行,但是我需要print
在刀片文件中的车辆categories
下的值.
It is working however I need print
its values under vehicles categories
in blade file.
我该如何实现?
图片
希望通过关系动态地做到这一点 我有2个模型,分别是类别和具有以下关系类别的车辆
hope to do this dynamicaly with relationship I have 2 models as Category and Vehicles with following relationship Category
public function vehicles()
{
return $this->hasMany(Vehicle::class);
}
public function category()
{
return $this->belongsTo(Category::class);
}
和类别表名称如下
id categoryname images
1 Car car.png
2 Van van.png
3 SUV suv.png
etc
那么我如何使用车辆表从类别表和类别值计数中打印类别名称和图像,并在同一循环中全部打印?
then how can I print categoryname and images from categories table and categoryname values counts using vehicles table and print all in same loop?
推荐答案
在Controller中添加groupBy()
:
Add groupBy()
in Controller:
$names = Vehicle::groupBy('categoryname')->select('id', 'categoryname', \DB::raw('COUNT(*) as cnt'))->get()->groupBy('categoryname');
刀片中:
@foreach($names as $key => $name)
<div class="col-md-3 text-center">
<img src="{{ URL::asset('/images/'.$name->images) }}" alt="{{ $key }}" height="50" width="50" class="center-block">
<div>{{ $key }} ({{ $name->count() }})</div>
<div>text text text text</div>
</div>
@endforeach
*保持图像名称与类别名称相同.
*Keep image name same as the category name.
这篇关于如何计算表列值并在刀片文件laravel 5.6中打印的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!